[英]How to use DataInputStream to read binary data from a file and print to the console?
這是問的問題:編寫一個程序,使用 DataInputStream 從 binary.txt 讀取行星詳細信息,並在標准輸出上打印行星詳細信息。
但是,下面的程序會拋出一個 IOException。 我無法弄清楚問題所在。 任何幫助,將不勝感激。
import java.io.*;
public class LA4ex2b {
public static void main(String[] args) throws IOException {
DataInputStream input=null;
try
{
input= new DataInputStream(new FileInputStream("C:/Users/user/workspace/LA4ex2a/binary.txt"));
String str;
// read until the string read is null i.e. read till end of file
while ((str = input.readUTF()) != null) {
String token[] = str.split(" "); // tokenizes the string with
// space as a delimeter
for (int i = 0; i <token.length; i++)
{
if (IsDouble.IsaDouble(token[i]))
System.out.print(Double.parseDouble(token[i]));
else
System.out.print(token[i]);
}
}
}
catch (IOException e) {
e.printStackTrace();
}
finally
{
if (input!= null)
input.close();
}
}
}
如果您正在讀取二進制文件,則不能假設它是作為文本存儲的。
相反,您必須事先知道每個字段數據類型是什么,並像這樣閱讀它們
DataInputStream input= new DataInputStream(new FileInputStream(new File("xyz")));
double d = input.readDouble();
int i = input.readInt();
char c = input.readChar();
正如你所看到的,有“水星”——行星名稱——但沒有雙“1.23”的文本表示,所以它實際上是二進制數據。 也許input.readDouble ? 始終在 Internet 上搜索 javadoc。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.