0

I need to read an integer from a non-text file in Java. Here is the equivalent code in C

unsigned int MagicNumber;
int fd = open("MyFile", O_RDONLY);
int rc = read(fd, &MagicNumber, 4);

What is the equivalent in Java?

This does NOT work for me (it produces different results than the C code):

FileInputStream fin = new FileInputStream("MyFile");
DataInputStream din = new DataInputStream(fin);
int MagicNumber = din.readInt();
JB_User
  • 3,117
  • 7
  • 31
  • 51

1 Answers1

0

Java uses a machine independent representation of the interger as a byte sequence, if you write it with DataOutputStream and next try to read it with DataInputStream on a different machine even with different endian, it will read it correctly anyway. Java was designed exactly for that: i.e. to be machine independent.

Of course you cannot assume the byte sequence will be the same in the file you generated in C.

It happens that Java defaults to big-endian (see the DataOutput specs). If you do your test on any big-endian machine it will work, on a little-endian (like x86) it will fail.

You can try to use LittleEndianDataOutputStream to solve this.

user1708042
  • 1,740
  • 17
  • 20