EOFException - 如何处理?
我是一个初学者Java程序员,遵循java教程。
我正在使用Java教程的Data Streams页面中的简单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
如果这意味着我应该处理它,请告诉我如何做到这一点。
编辑
根据建议,我已通过使用 for 循环条件修复了它。in.available() > 0
while
或者,我无法执行任何操作来处理异常,因为它很好。