java nio transferTo方法使用场景
java nio transferTo方法最多只能发送2G的数据,超过2G需要循环发送-零拷贝
文件拷贝
try (FileChannel inputChannel = new FileInputStream(sourceFile).getChannel();
FileChannel outputChannel = new FileOutputStream(destFile).getChannel()) {
long position = 0;
long size = inputChannel.size();
while (position < size) {
long transferred = inputChannel.transferTo(position, size - position, outputChannel);
if (transferred <= 0) {
break;
}
position += transferred;
}
}
将文件直接发送到客户端 Socket(Web 文件服务器最常见场景)
import java.io.*;
import java.net.*;
import java.nio.channels.*;
public class FileServerZeroCopy {
public static void main(String[] args) throws IOException {
int port = 8080;
ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.bind(new InetSocketAddress(port));
System.out.println("Listening on port " + port);
while (true) {
SocketChannel client = serverChannel.accept();
sendFile(client, new File("big-file.zip"));
client.close();
}
}
public static void sendFile(SocketChannel client, File file) throws IOException {
try (FileChannel fileChannel = new FileInputStream(file).getChannel()) {
long position = 0;
long size = fileChannel.size();
while (position < size) {
long transferred = fileChannel.transferTo(position, size - position, client);
if (transferred <= 0) break;
position += transferred;
}
}
}
}