Reputation: 14584
I'm trying to familiarize myself with Java IO classes, so I wrote the code below:
public static void main(String[] args)throws IOException {
FileOutputStream fos = new FileOutputStream("fileIO.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
DataOutputStream dos = new DataOutputStream(bos);
//fos.write(9999);
//bos.write(9999);
dos.writeInt(9999);
dos.writeBytes("中文字(Chinese)\n");
dos.writeChars("中文字(Chinese)\n");
dos.flush();
FileInputStream fis = new FileInputStream("fileIO.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
System.out.println(dis.readInt());
System.out.println(dis.readUTF());
}
Unfortunately, I get this:
9999
Exception in thread "main" java.io.EOFException
at java.io.DataInputStream.readFully(DataInputStream.java:180)
at java.io.DataInputStream.readUTF(DataInputStream.java:592)
at java.io.DataInputStream.readUTF(DataInputStream.java:547)
at IO.main(IO.java:34)
Could anyone point out why? Thanks.
Upvotes: 1
Views: 9024
Reputation: 137442
I think this link will be helpful. The exception is thrown (from oracle docs) -
if this input stream reaches the end before reading all the bytes.
Upvotes: 1
Reputation: 311052
You can only use readUTF()
to read items that were written with writeUTF()
.
This is true in general for readXXX()
and writeXXX()
for any XXX (unless you want to read the bytes of an int or some such and you know what you're doing).
Upvotes: 1
Reputation: 533890
When you perform a readUTF, the first two byte are used for the length. This means if you have random bytes there (not from writeUTF) you will attempt to read very long string instead and as there is not enough data, you will get EOFException.
Upvotes: 3
Reputation: 12883
Instead of
dos.writeBytes("中文字(Chinese)\n");
dos.writeChars("中文字(Chinese)\n");
you need
dos.writeUTF("中文字(Chinese)\n");
Upvotes: 4
Reputation: 26809
You haven't UTF char after Integer number in your file. When you're trying read UTF there is End of File so you have the exception.
Try in debug mode stop before you read and check manually to your file, what do you have then?
Upvotes: 0