ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
~~~ package com.youge.nio.zerocopy; /** * @author: hcf * @qq: 46914685 * @email: 46914685@qq.com * @date: 2020/11/27 11:56 */ import java.io.FileInputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.FileChannel; import java.nio.channels.SocketChannel; /** * NIO来传输读写文件 */ public class NewIOClient { public static void main(String[] args) throws IOException { //获取socketChannel SocketChannel socketChannel = SocketChannel.open(); //连接服务器 boolean connect = socketChannel.connect(new InetSocketAddress("127.0.0.1",7002)); String fileName="phpstudy_install.dmg"; //得到一个文件channel FileChannel fileChannel = new FileInputStream(fileName).getChannel(); //准备发送 long startTime = System.currentTimeMillis(); //在linux下就transferTo()方法就可以完成传输 //在windows下调用transferTo()方法,一次只能发送8M的数据.如大于8M的数据,需要分段传输文件,需要记录传输时的位置 //transferTo()方法底层使用到了零拷贝 long transferCount = fileChannel.transferTo(0, fileChannel.size(), socketChannel); System.out.println("发送总字节数:"+transferCount+",耗时:"+(System.currentTimeMillis()-startTime)); //释放资源 fileChannel.close(); socketChannel.close(); } } ~~~