我正在使用此代码读取 Java 中的文件
import java.io.*;
public class IOReadDataStreams {
public static void main(String[] args)throws IOException{
DataInputStream in = null;
try{
in = new DataInputStream(
new BufferedInputStream(new FileInputStream("invoicedata")));
int unit;
double price;
String desc;
while(true){
unit = in.readInt();
price = in.readDouble();
desc = in.readUTF();
System.out.println(unit+" " + price +" "+ desc);
}
}catch(EOFException e){
e.printStackTrace();
}
finally{
if(in != null)
in.close();
}
}
}
我尝试读取的文件是由这段代码制作的
import java.io.IOException;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
public class IODataStreams {
static final String dataFile = "invoicedata";
static final double[] prices = new double[]{19.99, 9.99,15.99,3.99,4.99};
static final int[] unitCount = new int[]{12,8,13,29,50};
static final String[] desc = new String[]{
"Java T Shirt",
"C# T Shirt",
"PHP T Shirt",
"Ruby T Shirt",
"Go! T Shirt"
};
public static void main(String[] args) throws IOException{
DataOutputStream out = null;
DataInputStream in = null;
try{
out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("invoicedata")));
for(int i = 0 ; i < prices.length; i++){
out.writeUTF(desc[i]);
out.writeInt(unitCount[i]);
out.writeDouble(prices[i]);
}
}finally{
if(out != null)
out.close();
}
}
}
现在我想知道为什么我的第一个代码(读取文件的代码)不是 打印价格,描述和单位。 它不断返回一个 EOFException
错误专门在此行上
desc = in.readUTF();
您按以下顺序写入数据:
out.writeUTF(desc[i]);
out.writeInt(unitCount[i]);
out.writeDouble(prices[i]);
但是以错误的顺序读取数据:
unit = in.readInt();
price = in.readDouble();
desc = in.readUTF();
您需要以相同的顺序读取和写入数据,特别是UTF
位,因为这不会转换为数字。
当我切换这些行以使读取和写入顺序相同时,IOReadDataStreams
输出的内容如下:
12 19.99 Java T Shirt
8 9.99 C# T Shirt
13 15.99 PHP T Shirt
29 3.99 Ruby T Shirt
50 4.99 Go! T Shirt
在到达文件的EOF并抛出(像它应该一样)EOFException之前。