简体   繁体   中英

FileChannel - append byte buffer at eof?

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.

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.

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