Reputation: 1293
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.
Upvotes: 0
Views: 1570
Reputation: 310957
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.
Upvotes: 2