DataInputStream deprecated readLine() method

感情迁移 提交于 2019-11-28 21:09:26

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

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.

user3950170

The below doesn't work,

num = Integer.parseInt(in);

Instead you should use:

num = Integer.parseInt(in.readLine());

readLine() will read an input of line until line break.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!