简体   繁体   中英

RandomAccessFile unexpected behavior for seek and write or write with offset

I cannot understand what is the difference between

RandomAccessFile raf = new RandomAccessFile(file, "rw");
int offset = getOffset();
byte[] dataInBytes = getData();
raf.seek(offset);
raf.write(dataInBytes, 0, getSize())'

and

...
byte[] dataInBytes = getData();
raf.write(dataInBytes, offset, getSize());

I thought seeking and then writing is equivalent to using write function with offset instead of zero. But seems it is not the case. I do not know what's the difference yet, I just need to pass unit tests, and second version passes unit tests and the first does not.

What is the difference between those two approaches?

Look at the JavaDoc of RandomAccessFile#write(byte[]. int, int) :

Writes len bytes from the specified byte array starting at offset off to this file.
Parameters :
b - the data.
off - the start offset in the data.
len - the number of bytes to write.

The offset parameter that you pass into write(byte[], int, int) is not an offset into the file, but an offset into the byte array that you pass.

Your first code snippet positions the RandomAccessFile at position offset and then writes getSize() bytes from the beginning of the data array at that position.

Your second code snippets does not change the position within the RandomAccessFile (that probably means starting to write at the beginning of the file) and then writes getSize() bytes of the data array, beginning with the byte at position offset in the byte array.

In the former the offset is into the file you are accessing. In the later it is an offset into the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM