簡體   English   中英

DataInputStream 已棄用 readLine() 方法

[英]DataInputStream deprecated readLine() method

我在 java 6. Using 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()讀取一行。

更多選擇:

  • 使用圍繞System.in構建的Scanner ,並調用Scanner.nextLine
  • 使用Console (從System.console()獲得)並調用Console.readLine

棄用和替代方案通常已在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也是一個很好的(和現代的)替代方案。

下面不行,

num = Integer.parseInt(in);

相反,您應該使用:

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

readLine()將讀取 line 的輸入直到換行。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM