开发者

Java DataInputStream read operations throwing Exceptions

开发者 https://www.devze.com 2023-02-20 15:57 出处:网络
I\'m trying to familiarize myself with Java IO classes, so I wrote the code below: public static void main(String[] args)throws IOException {

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.DataInputStr开发者_Python百科eam.readUTF(DataInputStream.java:592)
at java.io.DataInputStream.readUTF(DataInputStream.java:547)
at IO.main(IO.java:34)

Could anyone point out why? Thanks.


Instead of

dos.writeBytes("中文字(Chinese)\n");
dos.writeChars("中文字(Chinese)\n");

you need

dos.writeUTF("中文字(Chinese)\n");


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.


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).


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.


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号