Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataInputStream deprecated readLine() method

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.

like image 566
Some Java Guy Avatar asked Apr 10 '11 11:04

Some Java Guy


People also ask

Why DataInputStream is deprecated?

DataInputStream has been deprecated because it does not properly convert bytes to characters.

What is dis readLine () in Java?

The readLine() method of Console class in Java is used to read a single line of text from the console. Syntax: public String readLine() Parameters: This method does not accept any parameter. Return value: This method returns the string containing the line that is read from the console.


2 Answers

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
like image 137
Jon Skeet Avatar answered Sep 17 '22 16:09

Jon Skeet


Deprecation and the alternatives is usually already explicitly explained in the javadocs. So it would be the first place to look for the answer. For DataInputStream you can find it here. The readLine() method is here. Here's an extract of relevance:

Deprecated. This method does not properly convert bytes to characters. As of JDK 1.1, the preferred way to read lines of text is via the BufferedReader.readLine() method. Programs that use the DataInputStream class to read lines can be converted to use the BufferedReader class by replacing code of the form:

    DataInputStream d = new DataInputStream(in); 

with:

    BufferedReader d          = new BufferedReader(new InputStreamReader(in)); 

The character encoding can then be explicitly specified in the constructor of InputStreamReader.

The Scanner which was introduced since Java 1.5 is also a good (and modern) alternative.

like image 35
BalusC Avatar answered Sep 19 '22 16:09

BalusC