【发布时间】:2021-03-17 09:57:12
【问题描述】:
在 Java 代码中,我有一个使用 MappedByteBuffer 映射的文件区域,我需要将其发送到客户端(写入 Outputstream)。我需要确保在发送/写入套接字时,由于内存限制,它不会创建任何副本。我怎样才能做到这一点? Bytebuffer.array() 会达到这个目的吗?
分享代码。注意:FileChannel 是只读的,我需要按原样发送 ByteBuffer 数据。
private void writeData(Socket clientSocket, MappedByteBuffer byteBuffer){
Path path = Paths.get(myfile);
MappedByteBuffer memoryMappedBuffer = null;
try (FileChannel fChannel = FileChannel.open(path, StandardOpenOption.READ)) {
memoryMappedBuffer = fChannel.map(FileChannel.MapMode.READ_ONLY, location, size);
}catch(){
//How can i write memoryMappedBuffer to socket outputStream without copying data...? like
clientSocket.getOutputStream().write(memoryMappedBuffer .array());
}
【问题讨论】:
标签: java nio java-io virtual-memory memory-mapped-files