nio 使用channel 复制文件

该博客通过Java代码展示了NIO与IO在文件复制操作上的性能对比。实验中,博主使用了两种不同的方法,一是传统的IO流进行复制,二是使用NIO的ByteBuffer。结果显示,NIO在执行时间上比IO有优势。此内容对于理解Java中I/O操作的性能差异有参考价值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class ChannelTest {
    public static void main(String[] args) throws IOException {

        FileInputStream inputStream = new FileInputStream("H:/e-touch-etx.zip");
        FileChannel inputStreamChannel = inputStream.getChannel();
        FileOutputStream fileOutputStream = new FileOutputStream("H:/e-touch-bak.zip");
        FileChannel channel = fileOutputStream.getChannel();

        ByteBuffer allocate = ByteBuffer.allocate(1024);
        byte[] bytes = new byte[1024];
        long l1 = System.currentTimeMillis();
       /* while (inputStreamChannel.read(allocate)!= -1){
            allocate.flip();
            channel.write(allocate);
            allocate.clear();
        }*/
        long l2 = System.currentTimeMillis();

        int len =  -1 ;
        while ((len = inputStream.read(bytes))!= -1){
            fileOutputStream.write(bytes,0,len);
        }
        long l3 = System.currentTimeMillis();
        System.out.println("nio 执行耗费时间位 "+(l2-l1));
        System.out.println("io 执行耗费时间位 "+(l3-l2));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值