filechannel是java nio中支持随机访问的高效文件i/o类,可通过fileinputstream/fileoutputstream、randomaccessfile或files.newbytechannel获取;通过position()定位,配合bytebuffer实现读写;需注意线程安全、资源释放及单次write可能未写完。

FileChannel 是 Java NIO 中用于高效、非阻塞式文件 I/O 的核心类,支持在文件任意位置进行读写(即“随机访问”),比传统 FileInputStream/FileOutputStream 更灵活,尤其适合大文件处理或需要跳转读写的场景。
1. 获取 FileChannel 的三种常用方式
FileChannel 不能直接 new,必须通过以下任一渠道获得:
-
通过 FileInputStream / FileOutputStream 获取(仅限读或写):
FileInputStream fis = new FileInputStream("data.txt");<br> FileChannel rChannel = fis.getChannel(); // 只读FileOutputStream fos = new FileOutputStream("data.txt", true);<br> FileChannel wChannel = fos.getChannel(); // 只写(追加模式下 position 在末尾) -
通过 RandomAccessFile 获取(读写兼备,最常用):
RandomAccessFile raf = new RandomAccessFile("data.txt", "rw");<br> FileChannel channel = raf.getChannel(); // 支持读 + 写 + 定位 -
通过 Files.newByteChannel()(推荐用于 JDK 7+):
Path path = Paths.get("data.txt");<br> FileChannel channel = Files.newByteChannel(path, StandardOpenOption.READ, StandardOpenOption.WRITE);
2. 定位到指定位置:position() 方法
FileChannel 维护一个内部的当前读写位置(类似文件指针),用 position(long) 设置,用 position() 查询:
-
channel.position(1024);→ 下次读/写从第 1024 字节(0 起始)开始 -
long pos = channel.position();→ 获取当前偏移量 - 注意:设置 position 超出文件当前长度是允许的(写入时会自动扩展文件,中间填充 0x00)
3. 随机读写数据:read() 和 write() 配合 ByteBuffer
FileChannel 不操作字节数组,而是与 ByteBuffer 协同工作。关键点:
-
读取:先
buffer.clear()(重置 limit=capacity, position=0),再调用channel.read(buffer),数据写入 buffer;之后buffer.flip()切换为读模式,才能安全获取内容 -
写入:先
buffer.flip()(使 position=0, limit=之前 position),再调用channel.write(buffer),将 buffer 中 [0, limit) 数据写入当前位置 - 示例:在第 512 字节处写入字符串 "ABC"
String data = "ABC"; ByteBuffer buf = StandardCharsets.UTF_8.encode(data); channel.position(512); channel.write(buf); // 自动更新 position
4. 注意事项与常见陷阱
- 线程安全:FileChannel 实例本身不是线程安全的,多线程并发读写需手动同步(如 synchronized 块或使用独立 channel)
-
资源释放:务必显式调用
channel.close()和底层流/RAF 的close(),建议用 try-with-resources - 写入长度限制:单次 write() 不保证写完全部 buffer,返回值是实际写入字节数,需循环处理(除非确定 buffer 很小)
-
内存映射替代方案:对超大文件高频随机访问,可考虑
channel.map()获取 MappedByteBuffer,性能更高但有内存和平台限制
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











