35

我在 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() 时进行解释。

4

4 回答 4

36

InputStream本质上是一个二元结构。如果您想读取文本数据(例如从控制台),您应该使用 a Readerof some description。要将 a 转换InputStreamReader,请使用InputStreamReaderBufferedReader然后在周围创建一个Reader,您可以使用 读取一行BufferedReader.readLine()

更多选择:

  • 使用Scanner内置回合System.in,然后调用Scanner.nextLine
  • 使用 a Console(从 获得System.console())并调用Console.readLine
于 2011-04-10T11:20:37.133 回答
29

弃用和替代方案通常已在javadocs中明确解释。所以这将是寻找答案的第一个地方。因为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也是一个很好的(和现代的)替代方案。

于 2011-04-10T11:27:31.313 回答
0

以下不起作用,

num = Integer.parseInt(in);

相反,您应该使用:

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

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

于 2014-08-17T14:56:32.290 回答
0

在 scala 中调用readLine命令会返回“警告:有一个弃用警告;使用 -deprecation 重新运行以获取详细信息”消息。

您可以如下图所示处理此警告

val hadoopConfig = spark.sparkContext.hadoopConfiguration
val hdfs = org.apache.hadoop.fs.FileSystem.get(hadoopConfig)
val destinationFile = new org.apache.hadoop.fs.Path(s"hdfs://...")
val outFile = hdfs.open(destinationFile)

val wholeStream = Array.fill[Byte](outFile.available)(0)
outFile.readFully(wholeStream,0,outFile.available)
return new String(wholeStream)
于 2020-01-16T12:15:30.880 回答