【问题标题】:DataInputStream deprecated readLine() methodDataInputStream 不推荐使用 readLine() 方法
【发布时间】:2011-08-02 10:54:42
【问题描述】:

我在 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() 被弃用时,请解释一下。

【问题讨论】:

  • 下次请包含一个可编译的测试用例(或带有适用错误的失败测试用例)。
  • 测试用例?我们在谈论弃用。您将上面的代码放入编辑器中,它会将行变成黄色并说“不推荐使用 readLine”。没有人需要一个测试用例被告知 Java 方法已被弃用。这是适用的警告:docs.oracle.com/javase/7/docs/api/java/io/…

标签: java user-input readline datainputstream


【解决方案1】:

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

更多选择:

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

【讨论】:

    【解决方案2】:

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

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

        DataInputStream d = new DataInputStream(in);
    

    与:

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

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

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

    【讨论】:

      【解决方案3】:

      下面的不行,

      num = Integer.parseInt(in);
      

      你应该使用:

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

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

      【讨论】:

        【解决方案4】:

        在 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)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-12-13
          • 2014-05-05
          • 2012-02-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多