Search code examples
javadataoutputstreamrandomaccessfile

Problems reading from binary file or creating it


When I create the file I use the dataoutputstream to write one 'int' at a time:

Database.write(0)

Of course it doesn't say 0 it's a variable there but I printed it and the first one is 0 so I'm taking that one as an example.

Now I'm not 100% sure, but only using that line of code my file should now contain:

0000 0000 0000 0000 0000 0000 0000 0000

right?

So when I'm trying to read the very first 4 bytes using:

RandomAccessFile raf = new RandomAccessFile("Database", "r");
raf.seek(0);

byte[] ByteArr = new byte[4];
raf.read(ByteArr, 0, ByteArr.length);

ByteArr should contain just 0's?

Well I printed the Byte[] and this is what I get:

0
4
13
-126

Kind Regards Captain Confused


Solution

  • The write() method writes a single byte to file. Its parameter is an int, but that int is assumed to be in the range [0, 255].

    If you want to write a full 4-byte int to file, use the writeInt() method. Otherwise, to retrieve just the value 0 again, read one byte from the file using read().

    As a side note, RandomAccessFile can handle both reads and writes, so you should use it for both.