Read interactive command-line input with Java

Java command-line FAQ: How do I read command line input from a Java application (interactively)?

Update: After reading this article, please look at the Comments section below for a newer version of my command line input class, which now uses the Java 5 Scanner class.

Introduction - Reading Java command line input

While Java is generally used to create applets, servlets, and general-purpose applications, you may occasionally need to create applications that interactively communicate with a user at a command-line prompt, such as a Unix or DOS prompt. In these cases you'll see a prompt that looks something like this:

Enter your name: _

Unfortunately, this is one area where it's difficult to use vanilla Java methods. If you're used to simple echo and read statements in shell scripts, you're in for a bit of shock. I suspect the creators of Java didn't expect to see their language used for this purpose, or they just assumed developers would create their own classes to simplify this process.

In this article I present a technique you can use when creating Java programs that require interactive command-line input. If you like this basic technique, and would like to see expanded coverage of how to read numeric values, or would like to see a custom class for handling command-line input, just leave a comment below, and I'll provide a follow-up as quickly as we can.

Reading a string the user enters at a command-line prompt

The basic technique of reading a String provided by a user at a command-line is fairly simple, but more lengthy than you'd expect. It involves the use of the System.in object, along with the InputStreamReader and BufferedReader classes. (See my Java BufferedReader examples for more information on those classes.)

The code below shows how you can prompt the user to enter a String value, such as their name, and then read that value:

import java.io.*;

public class ReadString {

   public static void main (String[] args) {

      //  prompt the user to enter their name
      System.out.print("Enter your name: ");

      //  open up standard input
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

      String userName = null;

      //  read the username from the command-line; need to use try/catch with the
      //  readLine() method
      try {
         userName = br.readLine();
      } catch (IOException ioe) {
         System.out.println("IO error trying to read your name!");
         System.exit(1);
      }

      System.out.println("Thanks for the name, " + userName);

   }

}  // end of ReadString class

That code demonstrates how you can print a prompt to the user using the System.out.print() method. Notice that I use the print() method instead of println(). Using the print() method lets you keep the cursor on the same line of output as our printed text. This makes it look like a real prompt (instead of having the user's response appear on the line below your prompt).

Next, I read the user's input by passing the System.in object to the InputStreamReader and then into the BufferedReader The Java BufferedReader class gives us the readLine() method, and applies buffering to the input character input stream. Notice that the readLine() method can thrown an IOException error, so you have to enclose the statement in a try/catch statement.

Java command line input - final thoughts and source code

As you can see from the source code, reading Java command line input from a user is a little cumbersome. In the example I'm only prompting the user for one input value. Of course it gets more complicated if you want to read multiple input values, or if you want to read intergers or floating-point numbers. 

If you'd like to download the ReadString.java code shown in Listing 1, just click here, and the Java code will be displayed in your browser. Then just use the "File | Save As" option of your browser to save the source code to your system.

This was very helpful for me

This was very helpful for me as I am a beginner in Java.Thanks a lot.

I 'm too beginner in java.

I 'm too beginner in java. Thanks a lot for a good tutorial on basics of getting input from command line.

Nice

This helped me substantially! A well explained and accurate example, thanks!

Please explain

Can you please explain as to why do we use the System.in as an input to InputStreamReader, and the InputStreamReader as an input to BufferedReader.

Sure. System.in represents

Sure. System.in represents the standard input stream. As the System Javadoc states, "This stream is already open and ready to supply input data. Typically this stream corresponds to keyboard input or another input source specified by the host environment or user." So that's where we start to get the keyboard input.

The InputStreamReader is the "bridge from byte streams to character streams", so it helps perform that conversion, as I want to deal with keystrokes as characters in my code, and not bytes. (A different programmer might want to deal with them as bytes, but because I know I want to use the BufferedReader's readLine() method, I'm going down this road.)

The BufferedReader "Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines." I use it because the readLine() method makes it really easy to deal with the input as a String. If I didn't wrap it around the InputStreamReader, I'd have to use the InputStreamReader's read() method, which returns one character at a time.

cmd line method is great

thanks... i really learnt from it

its a nice way to explain .. n seems much simpler !!

Why so lengthy?

Why are you not using a Scanner object?

Scanner input = new Scanner( System.in );

Read command line input with Scanner

Thanks for the tip. To answer your question, this article was written before Java 5 and the Scanner class came around.

Here's an updated version of this class, demonstrating how to read command line input from a Java program using the Scanner class:

import java.util.Scanner;

public class ScannerTest
{

  public static void main (String[] args)
  {
    //  prompt the user to enter their name
    System.out.print("Enter your name: ");

    // get their input
    Scanner scanner = new Scanner(System.in);

    // there are several ways to get the input, this is 
    // just one approach
    String username = scanner.nextLine();

    // test the String
    if (username.trim().equals(""))
    {
      System.out.println("Hmm, I didn't get your name");
    }
    else
    {
      System.out.println("Thanks for the name, " + username);
    }
  }

}

As mentioned, there are several ways to get input from the Scanner class, and I recommend taking a look at the Scanner class javadoc.

is there a way to get user

is there a way to get user input without the scanner class?

Yes, just use the ReadString

Yes, just use the ReadString class shown near the top of this article. It was written before the Scanner class was available, so it just uses and InputStreamReader and BufferedReader.

is this prog wrong...?i did in netbeans, it not working.help me

import java.io.*;

public class BRRead
{

public static void main( String args []) throws IOException
{
char c;
BufferReader br=new BufferReader(new InputStreamReader(System.in));
System.out.println("Enter character, 'q' to quit");

do{
c = (chat) br.read();
System.out.println(c);
}while(c!='q');
}
}

Nice'n easy

Hi
This are nice snippets ...
I was able to plug-in your "input reader" snippet in to the "system exec" program and was able to interactively execute any system calls!!!
Like if I want to do a bioinformatics blast search I just have to pass the required parameters and it does the job:EG:

[feseha@voyager Jfiles]$ java JavaRunCommand2
Enter your command: bl2seq -i test1.fna -j test2.fna -p blastn

Ans it works like a charm ...

Cool stuff!
Thank you

Comment

Very good. You have shown me classic and new way to read input at command prompt from user. I want you explain more about Scanner class methods for primitive read operation.

use in netbean

Hello i am a very beginner in Java, if i willing to use this code in netbean, what module should i install? Before this i compile this coding on bluej but noting happen.. sorry asking this question but i am really want to know how to use it.

Corrected BufferedReader example

Here's a corrected version of your code:

import java.io.*;

public class BRRead
{
  public static void main( String args []) throws IOException
  {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter character, 'q' to quit");

    char c;
    while ( (c = (char)br.read()) != 'q')
    {
      System.out.println("char: " + c + ".");
    }
  }
}

You were very close, except for a few typos.

Also, sorry, I don't use NetBeans, and I don't know how to make this work from there. I just run it from the command line (Unix command line, in my case).

I hope that is helpful, and thanks for the nice "while loop" example of this code.

 

NetBeans

I'm sorry, I don't use NetBeans, and so I can't be much help here, but I thought I'd post your comment here in case someone else can answer it.

How to read numbers?

Hi,
I´m beggining with java and started making a simple program which counts the digits of the number entered by the user. This is where it all stops working, I tried using the Scanner, but apparently it can be used with string only.

Can anyone help?

import java.util.Scanner;

class NrDigits3 {
public static void main (String[] args) {

int d=1;
System.out.println ("Write the number of which you want to count the digits");

Scanner scanner = new Scanner(System.in);
int n = scanner.nextLine();

if (n<10)
{ System.out.println(d);}

while (n>= 10)
{n=n/10;
d++;
if (n<10)
{System.out.println(d);}
}
}
}

How to mask a command line password input in java

Hi,

I would like to know how to mask a password entered using command line.

I had gone through the code given by SUN microsystems for masking a password. But that thread runs into an infinite loop and it seems it has a bug.

I'm using Java 1.5.

Could you guys help me out...

Thanks.

How about passwords

What can be done for passwords. I would like to get input but I do not want it to be shown on the screen while it is being typed. How can I accomplish that?

Java Scanner with numbers

Sorry for the late reply, but the Scanner class has numeric methods like nextInt, nextFloat, etc., that should work. If for some reason those don't work, read the input as a String, and convert it to a number, as in this Java String to int example.

Java command line password input/masking

Masking passwords on the command line with Java is tricky business. If you know you're on a Unix system, you might be able to print something from your Java program to tell the terminal not to display the input the user types, and then set it back to normal when you're done. I haven't done this in a long time, but you can do it with the Unix stty command, or even with a simple echo statement.

A second approach is to have your Java program run a separate thread that masks the password as the user types it, essentially deleting each character after the user types it. This is shown in this Sun/Oracle password masking tip.

How to Read Numbers

If we Change slightly
.
.
.
.
int n = scanner.readInt();
.
.
.
It will be OK.

sacnner.nextInt();

I would imagine that you've figured this out by now, but just in case:

You've got your int set up right now to take a string by using the .nextLine() function of the Scanner class. What you want is the .nextInt(); function. That should clear up the issue for you.

How to read numbers and words separatly?

We have such command line (Monica 29 Dan 35 Michale 16)
I must to count the average of this numbers and to show these names with their ages.

Can you help me? Should I make an array firstly?

Read as String, then convert

Yes, I would just read them in as String objects, then convert the expected numbers to int with Integer.parseInt(). If you know the input should be a String followed by an int (then repeat) this is a good approach.

BufferedReader readLine()

Hi,

Thanks for your post dude, its really useful for replacing DataInputStream readLine() method which is deprecated.

Post new comment

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