【发布时间】:2013-08-29 08:41:31
【问题描述】:
我是一名初学者,关注java tutorials。
我正在使用来自Java tutorials 的Data Streams Page 的简单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.
来自Java tutorials 的Data Streams Page,它说:
请注意,DataStreams 通过捕获 EOFException 来检测文件结束条件,而不是测试无效的返回值。 DataInput 方法的所有实现都使用 EOFException 而不是返回值。
那么,这是否意味着捕获EOFException是正常的,所以只捕获它而不处理它就可以了,意味着到达文件末尾?
如果这意味着我应该处理它,请告诉我如何处理。
编辑
根据建议,我已通过将 in.available() > 0 用于 while 循环条件来修复它。
或者,我无法处理异常,因为它很好。
【问题讨论】:
-
删除
e.printStackTrace();块中的e.printStackTrace();将删除异常堆栈跟踪的打印。而不是打印它,你应该记录它。