Java code to read command-line input

Java command-line FAQ: How do I read command-line input in a Java application?

Note: To see a more modern approach to this problem, see my article, How to read interactive command-line input in Java. That article demonstrates the use of the Java Scanner class, which came into existence as of Java 5.

I saw the following Java source code in some sample programs that Sun provides with OpenSSO, and I thought I'd show it here. This example code shows how to read command-line input from a Java program, or at least their approach to reading command line input.

Java code to read command line input

As you can see from this Java program, it prompts the user to enter several parameters from the command line, and it doesn't care whether that command line is DOS, Unix, Linux, or something else. It uses a combination of System.in, InputStreamReader, and BufferedReader to get the command-line input from the user.

Here's the main method from one of the sample classes. Note that I've commented-out the portions of the code that are not related to reading input from the user.

public static void main(String[] args) throws Exception
{
    System.out.print("Realm (e.g. /): ");
    String orgName = (new BufferedReader(new InputStreamReader(System.in))).readLine();

    System.out.print("Login module name (e.g. DataStore or LDAP): ");
    String moduleName = (new BufferedReader(new InputStreamReader(System.in))).readLine();

    System.out.print("Login locale (e.g. en_US or fr_FR): ");
    String locale = (new BufferedReader(new InputStreamReader(System.in))).readLine();

    //Login login = new Login(moduleName, orgName, locale);
    //AuthContext lc = login.getAuthContext();
    //if (login.login(lc))
    //{
    //  login.logout(lc);
    //}
    //System.exit(0);
}

For more robust needs there are probably libraries out there to handle this even better, but for a simple command-line program like this, this is a nice, simple approach.

Permalink

can u tell me y "throws Exception" has been used after the string args???

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.