DataInputStream不推荐使用readLine()方法

我在java 6.使用DataInputStream in = new DataInputStream(System.in); 阅读用户输入。 不推荐使用readLine()时。 阅读用户价值的工作是什么?

 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) { } 

请在不推荐使用readLine()时解释。

InputStream基本上是一个二进制构造。 如果要读取文本数据(例如,从控制台),您应该使用某些描述的Reader 。 要将InputStream转换为Reader ,请使用InputStreamReader 。 然后在Reader周围创建一个BufferedReader ,您可以使用BufferedReader.readLine()读取一行。

更多选择:

  • 使用内置Scanner System.in ,并调用Scanner.nextLine
  • 使用Console (从System.console() )并调用Console.readLine

通常已经在javadoc中明确解释了弃用和替代方案。 所以这将是第一个寻找答案的地方。 对于DataInputStream您可以在此处找到它。 readLine()方法在这里 。 这是相关的摘录:

不推荐 。 此方法无法将字节正确转换为字符。 从JDK 1.1开始,读取文本行的首选方法是通过BufferedReader.readLine()方法。 使用DataInputStream类读取行的程序可以通过替换表单的代码转换为使用BufferedReader类:

  DataInputStream d = new DataInputStream(in); 

有:

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

然后可以在InputStreamReader的构造函数中显式指定字符编码。

自Java 1.5以来引入的Scanner也是一个很好的(和现代的)替代品。

以下不起作用,

 num = Integer.parseInt(in); 

相反,你应该使用:

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

readLine()将读取行的输入直到换行。