简体   繁体   中英

RandomAccessFile: Getting Java.io.EOFException

I have the code:

junk.writeUTF("Jim");
junk.writeInt(9304029);
junk.writeUTF("England");

junk.writeUTF("Bob");
junk.writeInt(99291933);
junk.writeUTF("Canada");

junk.seek(12);
String name = junk.readUTF();
int number = junk.readInt();
String city = junk.readUTF();

When I run it I am getting the error message saying it's null. I get why this is happening but how do I know which byte to seek to so I can read the data for Bob? seek(12) is giving null.

int isn't 2 bytes, it's 4. And writeUTF writes a 2-byte length prefix, so the total length is supposed to be 18.

If we consider the offsets of each piece of data:

            Offset
UTF length  0
Jim         2
9304029     5
UTF length  9
England     11

When you pass in 12, it will try to read a UTF string using ng as the length, which is 28263, which is obviously a bit longer than your file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM