I'm working on a project in Java with a large binary file from which I always want to read and write small fragments (for writing I'll fill the remainder with padding). Now, when reading a file with InputStream
I can use the built-in skip(long)
method to jump to the offset I'm interested in.
The problem arises when I try to write to the OutputStream
. Since it is guaranteed to be a FileOutputStream
, I can use methods like getChannel()
to retrieve the stream's FileChannel
, with which I can then jump to a specific offset before passing the stream on to the actual writing function.
I've written the following code snippet to demonstrate my problem. The file
initially contains 6 bytes with ASCII values "abcdef"
(excluding the quotation marks), so writing 'X'
to the 4th index should yield "abcdXf"
.
try (FileOutputStream fos = new FileOutputStream(file)) {
FileChannel fc = fos.getChannel();
fc.position(4L);
fos.write('X');
} catch (IOException e) {
e.printStackTrace();
}
Problem is, when opening the resulting file with a hex editor, I instead get a 5-byte file with 4 zero bytes followed by the 'X'
I originally inserted into the file; which is what I wanted, only that now the file has shrunk and everything preceding the 'X'
has been set to 0.
Can anyone tell me what I'm doing wrong in that piece of code and how to properly use FileChannel
or other frameworks to achieve my goal?