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()
将读取行的输入直到换行。