DataInputStream deprecated readLine() method

Some Java Guy picture Some Java Guy · Apr 10, 2011 · Viewed 66.9k times · Source

I am on java 6. Using DataInputStream in = new DataInputStream(System.in); to read user input. When the readLine() is deprecated. What is the work around for reading user value?

DataInputStream in = new DataInputStream(System.in);
int num;
try
{
  num = Integer.parseInt(in.readLine()); //this works

  num = Integer.parseInt(in);  //just in doesnt work.
}
catch(Exception e)
{
}

please explain as it should when the readLine() is deprecated.

Answer

Jon Skeet picture Jon Skeet · Apr 10, 2011

InputStream is fundamentally a binary construct. If you want to read text data (e.g. from the console) you should use a Reader of some description. To convert an InputStream into a Reader, use InputStreamReader. Then create a BufferedReader around the Reader, and you can read a line using BufferedReader.readLine().

More alternatives:

  • Use a Scanner built round System.in, and call Scanner.nextLine
  • Use a Console (obtained from System.console()) and call Console.readLine