Files
Knowledge/0 编程/java/java FileChannel.transferTo.md

622 B

如果你发送的数据来源于文件(且不需要在应用层修改),可以使用 transferTo 直接利用操作系统的 sendfile 系统调用,完全避免数据拷贝到用户空间:

FileChannel fileChannel = FileChannel.open(Paths.get("/path/to/file")); SocketChannel socketChannel = SocketChannel.open(); socketChannel.connect(address); // 将文件从 offset 开始,共 count 字节直接发往 socket fileChannel.transferTo(offset, count, socketChannel);

这种情况下,数据直接从文件系统的 page cache 进入 socket 缓冲区,完全不经过用户空间,零拷贝。