cmann
cmann

Reputation: 1980

How to read String in java that was written using python's struct.pack method

I have written information to a file in python using struct.pack eg.

out.write( struct.pack(">f", 1.1) );
out.write( struct.pack(">i", 12) );
out.write( struct.pack(">3s", "abc") );

Then I read it in java using DataInputStream and readInt, readFloat and readUTF. Reading the numbers works but as soon as I call readUTF() I get EOFException.

I assume this is because of the differences in the format of the string being written and the way java reads it, or am I doing something wrong?

If they are incompatible, is there another way to read and write strings?

Upvotes: 2

Views: 1200

Answers (1)

Dave Ray
Dave Ray

Reputation: 40005

The format expected by readUTF(), is documented here. In short, it expects a 16-bit, big-endian length followed by the bytes of the string. So, I think you could modify your pack call to look something like this:

s = "abc"
out.write( struct.pack(">H", len(s) ))
out.write( struct.pack(">%ds" % len(s), s ))

My Python is a little rusty, but I think that's close. It also assume that a short (the >H) is 16 bits.

Upvotes: 4

Related Questions