测试传输262M视频文件,所需时间约3s
transferTo方法作用:将一个通道的数据传输到另一个通道
参数1:position 从该通道所需传输字节的启示位置
参数2:count 所传字节的长度
参数3:WritableByteChannel 目标通道
public abstract long transferTo(long position, long count,
WritableByteChannel target)throws IOException;
使用案例:
FileInputStream inputFile = new FileInputStream("input.txt");
FileOutputStream outputFile = new FileOutputStream("output.txt");
FileChannel inputChannel = inputFile.getChannel();
FileChannel outputChannel = outputFile.getChannel();
long transferredBytes = inputChannel.transferTo(0, inputChannel.size(), outputChannel);
网络通道传输案例:
服务端
public void server1() throws IOException {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(9527));
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
FileChannel channel = new FileOutputStream("C:\\SwaggerToCL\\test.txt").getChannel();
while (true) {
//这玩意没建立连接会堵塞喔,直到有连接进来
SocketChannel accept = serverSocketChannel.accept();
long flag = 0;
while (flag != -1) {
flag = accept.read(byteBuffer);
byteBuffer.flip();
channel.write(byteBuffer);
byteBuffer.clear();
}
}
}
客户端
public void client1() throws IOException {
SocketChannel open = SocketChannel.open();
open.connect(new InetSocketAddress("127.0.0.1", 9527));
FileChannel channel = new FileInputStream("C:\\SwaggerToCL\\23.09.11-编程设码初始化介绍.mp4").getChannel();
long l = System.currentTimeMillis();
long length = channel.size();
long begin = 0;
long total = 0;
long sum = 0;
while (true) {
//linux和window一次传输数据长度不一样,文件可能需要多次传输
total = channel.transferTo(begin, length, open);
sum += total;//记录传输总字节
if (total < length) {//一次还没有传完
//设置开始位置
begin += total;
//长度
length -= total;
} else {
//传输完成
break;
}
}
long l1 = System.currentTimeMillis();
System.out.println("传输文件所需时间:" + (l1 - l) + "传输总字节:" + sum);
open.close();
channel.close();
}
结果