我是一名初学者Java程序员,正在跟随java教程。
我正在使用Java教程的数据流页面中的简单Java程序,在运行时它不断显示EOFException
。我想知道这是否正常,因为读取器最终必须到达文件末尾。
import java.io.*;
public class DataStreams {
static final String dataFile = "F://Java//DataStreams//invoicedata.txt";
static final double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };
static final int[] units = { 12, 8, 13, 29, 50 };
static final String[] descs = {
"Java T-shirt",
"Java Mug",
"Duke Juggling Dolls",
"Java Pin",
"Java Key Chain"
};
public static void main(String args[]) {
try {
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dataFile)));
for (int i = 0; i < prices.length; i ++) {
out.writeDouble(prices[i]);
out.writeInt(units[i]);
out.writeUTF(descs[i]);
}
out.close();
} catch(IOException e){
e.printStackTrace(); // used to be System.err.println();
}
double price;
int unit;
String desc;
double total = 0.0;
try {
DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(dataFile)));
while (true) {
price = in.readDouble();
unit = in.readInt();
desc = in.readUTF();
System.out.format("You ordered %d" + " units of %s at $%.2f%n",
unit, desc, price);
total += unit * price;
}
} catch(IOException e) {
e.printStackTrace();
}
System.out.format("Your total is %f.%n" , total);
}
}
它编译通过,但输出结果为:
You ordered 12 units of Java T-shirt at $19.99
You ordered 8 units of Java Mug at $9.99
You ordered 13 units of Duke Juggling Dolls at $15.99
You ordered 29 units of Java Pin at $3.99
You ordered 50 units of Java Key Chain at $4.99
java.io.EOFException
at java.io.DataInputStream.readFully(Unknown Source)
at java.io.DataInputStream.readLong(Unknown Source)
at java.io.DataInputStream.readDouble(Unknown Source)
at DataStreams.main(DataStreams.java:39)
Your total is 892.880000.
请注意,DataStreams通过捕获EOFException来检测文件末尾的条件,而不是测试无效返回值。所有DataInput方法的实现都使用EOFException而不是返回值。
那么,这是否意味着捕获EOFException
是正常的,只需捕获它而不处理它就可以了,这意味着已经到达文件末尾了吗?
如果这意味着我应该处理它,请告诉我如何处理。
编辑
根据建议,我已经通过使用in.available() > 0
来修复了while
循环条件。
或者,我可以不处理异常,因为这是可以接受的。
catch
块中删除e.printStackTrace();
将删除异常堆栈跟踪的打印。相反,您应该记录它而不是打印它。 - araknoidavailable()
不是用于测试流结束的方法。你编辑中提出的解决方案是无效的。 - user207421