Pregunta

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.

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top