2011-04-10 60 views
23

我在使用java 6.使用DataInputStream in = new DataInputStream(System.in);来读取用户输入。 readLine()被弃用时。阅读用户价值的工作是什么?DataInputStream不推荐使用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()不推荐时使用。

+0

下次请包括一个可编译的测试用例(或具有适用错误的失败测试用例)。 – 2011-04-10 11:43:56

+0

测试用例?我们正在讨论弃用。你把上面的代码放到一个编辑器中,它会将行变成黄色,并说“readLine已被弃用”。没有人需要测试用例被告知java方法已被弃用。以下是适用的警告:https://docs.oracle.com/javase/7/docs/api/java/io/DataInputStream.html#readLine() – 2016-07-22 02:24:43

回答

29

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

更多的抉择:

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

弃用,而且替代品通常已经在javadocs中有明确的解释。所以这将是第一个寻找答案的地方。对于DataInputStream,您可以找到它herereadLine()方法是here。以下是相关性的摘录:

弃用。此方法不能正确地将字节转换为字符。从JDK 1.1开始,读取文本行的首选方法是通过BufferedReader.readLine()方法。

DataInputStream d = new DataInputStream(in); 

与:

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

字符编码然后可显式地指定使用该DataInputStream类读取线可以被转换程序通过替换形式的代码来使用BufferedReader类在InputStreamReader的构造函数中。

自Java 1.5以来推出的Scanner也是一个很好的(和现代的)选择。

1

下面不起作用,

num = Integer.parseInt(in); 

相反,你应该使用:

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

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

相关问题