java nio 中读写文件的核心做法是获取 filechannel 实例,配合 bytebuffer 进行数据搬运。读取时调用 channel.read(buffer) 将文件内容填充进缓冲区,写入时调用 channel.write(buffer) 将缓冲区数据刷入文件。若遇到文件末尾(eof),read() 会返回 -1;若缓冲区为空或位置未变,write() 可能抛出异常或无效果,需提前翻转缓冲区。

FileChannel.open() 打开文件时指定模式有什么影响
打开 FileChannel 时必须明确指定访问模式,这决定了后续读写的权限和文件行为。使用 StandardOpenOption.READ 只能读取,写操作会失败;使用 WRITE 或 APPEND 才能写入。若同时需要读写,必须显式包含 READ 和 WRITE 选项。默认情况下,写入会覆盖原有内容,除非指定 APPEND 模式追加到末尾。

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class FileChannelDemo {
public static void main(String[] args) throws IOException {
Path path = Paths.get("test.txt");
// 以读写模式打开,不存在则创建
try (FileChannel channel = FileChannel.open(path,
StandardOpenOption.CREATE,
StandardOpenOption.READ,
StandardOpenOption.WRITE)) {
String data = "Hello NIO";
ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
writeBuffer.put(data.getBytes());
writeBuffer.flip();
int written = channel.write(writeBuffer);
System.out.println("Written bytes: " + written);
// 切换回读模式
writeBuffer.clear();
int read = channel.read(writeBuffer);
if (read != -1) {
byte[] content = new byte[read];
writeBuffer.get(content);
System.out.println("Read content: " + new String(content));
}
}
}
}
ByteBuffer.flip() 在读写切换中起什么作用
ByteBuffer.flip() 用于在写入完成后切换到读取状态。写入时,缓冲区的位置指针向后移动,记录已写入的数据量。调用 flip() 后,limit 被设为当前位置,position 重置为 0,从而让后续的 read() 或 get() 操作能正确遍历刚写入的数据。若不执行此步骤,缓冲区处于“只写”状态,读取操作将无法获取任何内容。

import java.nio.ByteBuffer;
public class BufferFlipDemo {
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(10);
// 写入阶段
buffer.put((byte) 'A');
buffer.put((byte) 'B');
System.out.println("After put: pos=" + buffer.position() + ", limit=" + buffer.limit());
// 切换阶段
buffer.flip();
System.out.println("After flip: pos=" + buffer.position() + ", limit=" + buffer.limit());
// 读取阶段
while (buffer.hasRemaining()) {
System.out.print((char) buffer.get());
}
}
}
当 FileChannel.read() 返回 -1 时代表什么
当 FileChannel.read() 返回 -1 时,表示已达到文件末尾(End Of File, EOF)。此时没有更多数据可供读取,程序应停止读取循环。这是 NIO 非阻塞 I/O 中判断文件结束的标准方式,不同于传统字节流的 read() 返回 0 表示空但继续尝试的行为。在实际开发中,需检查返回值是否为 -1 以避免无限循环或无效数据处理。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











