• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 222
  • Last Modified:

binary struct reading from file. How to?

I have a file written from MSVC++ 6.0 like:

typedef struct My_format{
short num_1;
char name_1[4];
short num_2;
char name_2[10];
This structure repeats every 256 bytes.
I have to read this from Java. The only class that has readShort() method is RandomAccessFile. Do I have to read the members of the struct one by one? Or is there any method to do buffered reading?
If I read in an array of bytes, how can I convert the corresponding bytes to short/char[] ?

1 Solution
If you use readShort (which is also in DataInputStream by the way) it cannot be guaranteed to work. In Java a short is guaranteed to be two bytes, and to have a specific byte order for the disk representation. Neither of these conditions is true in C. C does not guarantee that short is two bytes, only that it is not longer than an int. And there is no guarantees about byte order on disk whatsoever. That is machine dependent.
Also, a char in Java is a two byte quantity (to support Unicode).

So, assuming that all these things come together, and you have no portability concerns you can use readShort and readByte. The result of readShort would simply be assigned to a short variable, and the readByte would be assigned to a byte or character depending on your needs. You could achieve buffered reading by using a BufferedInputStream.

If they do not happen to correspond, I would recommend using the same BufferedInputStream and pulling characters with readByte and assembling them as needed, e.g.

BufferedInputStream bi=new BufferedInputStream(new FileInputStream("filename"));
DataInputStream di=new DataInputStream(bi);
short num=((short)di.readByte())<<8) | (((short)di.readByte())&0xff);

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now