package fiedata;
import java.io.*;
public class Main {
static final int[] prices = { 4500, 3000, 2500 };
static final String[] books = { "JAVA","PHP","Mysql"};
public static void main(String[] args) throws IOException {
DataOutputStream out=null;
out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("books.dat")));
for (int i = 0; i < prices.length; i ++) {
out.writeInt(prices[i]);
out.writeUTF(books[i]);
out.flush();
}
DataInputStream in=null;
in = new DataInputStream(new BufferedInputStream(new FileInputStream("books.dat")));
int price;
String book;
try {
while (true) {
price = in.readInt();
book= in.readUTF();
System.out.format("saved in file %s %d%n",book, price); }
}
catch (EOFException e) {
e.printStackTrace();
}
}
}
Why this code throws EOFException?
saved in file JAVA 4500
java.io.EOFException
saved in file PHP 3000
saved in file Mysql 2500
at java.io.DataInputStream.readInt(DataInputStream.java:375)
at fiedata.Main.main(Main.java:41)
Directly after the bit of code you copied the text goes on to say:
Notice that DataStreams detects an end-of-file condition by catching EOFException, instead of testing for an invalid return value. All implementations of DataInput methods use EOFException instead of return values.
So, no, it’s not Sun’s fault that you didn’t bother to read the explanation of the code.
And, before you go running off to use exceptions for flow control, know that doing such is considered to be poor programming, due to the relatively massive overhead of generating an exception verses simply testing conditions. Had they a choice in the case of DataInput, et al, they would not have done that way. (Feel free to contact Sun and suggest what return value could be used to indicate EOF when any value may be valid and expected)