Question

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

Was it helpful?

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.

OTHER TIPS

The problem is DataOutputStream.write(int b) actually only writes the least significant byte. If you want to write out 4 bytes you need to use DataOutputStream.writeInt(int)

You're writing something in Chinese and then trying to read it in English, of course it's not going to make sense. If you want to write using DataOutputStream, you must read using DataInputStream. As you see, a raw read won't understand the encoding that data streams use. Alternatively, you can read raw bytes, but then you'll have to write them as well, not use a DataOutputStream which encodes the data so that DataInputStream can decode it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top