【问题标题】:FileChannel - append byte buffer at eof?FileChannel - 在 eof 处附加字节缓冲区?
【发布时间】:2026-01-26 06:45:02
【问题描述】:

我想知道是否有可能添加 使用文件通道的位置方法将字节缓冲区保存到文件末尾。

我读到需要打开文件输出流 带有附加标志

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

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

但是不应该可以附加缓冲区吗 通过修改通道的位置。

"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);

我将不胜感激,因为文件 被覆盖。

【问题讨论】:

  • 显示证明它没有按规定工作的代码。
  • 第二个代码示例中没有为 FileOutputStream 设置附加标志是错字吗?

标签: java bytebuffer filechannel


【解决方案1】:

文件在第二个示例中被覆盖,因为您没有指定值为trueappend 参数。之后,将其定位在 EOF 处,只需将其定位为零。

【讨论】:

  • 所以文件输出流指定内容是否被覆盖或附加如 > 或 >>
  • @EJP:您在 Channel 中的位置确实很重要,但是在以非附加模式打开 Stream 时,它会清除文件内容(您应该在文件浏览器中看到它)和 channel.size() 将返回 0。如果你调用 position(1024),你应该得到一些未指定的前 1024 个字节,然后是你之后写的任何内容。
  • 所以如果我要截断一个文件,我也需要 flagg
  • @jam 要么你想追加到文件或者你想截断 它。不是同时两个。如果要截断它,可以省略参数或将其设置为 false。
  • @Alexander 同意,我指的是 OP 使用 position().