0

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?

linux_user36
  • 113
  • 1
  • 8
  • 1
    See [**Does FileOutputStream truncate an existing file**](https://stackoverflow.com/questions/15387567/does-fileoutputstream-truncate-an-existing-file/45100363). This is likely a duplicate of that question - I'll let others decide. Also - file offsets are zero-based, so `fc.position(4L);` sets the position to the 5th byte. – Andrew Henle Feb 06 '22 at 13:20
  • @AndrewHenle Thanks, I didn't think of that yet. Apart from that, any ideas on why the preceding contents are nullified? – linux_user36 Feb 06 '22 at 15:08

0 Answers0