0

I wondered if there is a possibility to add a byte buffer to the end of a file by using the file channel's position method.

I have read that it is neccessary to open the file output stream with the append flag

ByteBuffer byteBuffer = ...;
FileOutputStream fileOutputStream = new FileOutputStream("path/to/file", true);
FileChannel channel = fileOutputStream.getChannel();

channel.write(bytebuffer);
channel.force(true);
channel.close();

but shouldn't it be possible to append the buffer by modifiing the position of the channel.

"The size of the file increases when bytes are written beyond its current size"

ByteBuffer byteBuffer = ...;
FileOutputStream fileOutputStream = new FileOutputStream("path/to/file");
FileChannel channel = fileOutputStream.getChannel();

channel.position(channel.size()).write(bytebuffer);
channel.force(true);

I would be grateful for some explanations since the file gets overwritten.

user207421
  • 305,947
  • 44
  • 307
  • 483
jam
  • 1,253
  • 1
  • 12
  • 26

1 Answers1

2

The file gets overwritten in the second example because you didn't specify an append parameter with value true. After that, positioning it at EOF just positions it at zero.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • so the file outputstream specifies if the content get's overwritten or appended like > or >> – jam May 04 '16 at 11:02
  • @EJP: It does matter where your position in Channel is, but while opening the Stream in not-appending mode it clears the file content (you should see it in your file browser) and the *channel.size()* will return 0. If you would call *position(1024)* you should get some unspecified first 1024 bytes and then whatever you write afterwards. – Alexander May 04 '16 at 11:18
  • so if I would truncate a file I would need the flagg too – jam May 04 '16 at 11:22
  • @jam *Either* you want to *append* to the file *or* you want to *truncate* it. Not both at the same time. If you want to truncate it you can either omit the parameter or set it to false. – user207421 May 04 '16 at 11:36
  • @Alexander Agreed, I was referring to the OP's use of `position().` – user207421 May 04 '16 at 11:47