IO文件复制

 

使用两种方式复制1.2G文件差异不大,缓冲区设置影响也不大。

ioCopyFile newIoCopyFile 
缓冲区时间缓冲区时间
102449774102436653
204842632204835792
409641671409632142
819234022819238983
16384369831638436000

   

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class CopyFileTest {
    public static void main(String[] args) throws IOException {
        new CopyFileTest().ioCopyFile("X:\\archive.zip", "X:\\archive2.zip");
        new CopyFileTest().newIoCopyFile("X:\\archive.zip", "X:\\archive2.zip");
    }

    public void newIoCopyFile(String sourcePath, String destPath) throws IOException {
        FileInputStream fi = new FileInputStream(sourcePath);
        FileOutputStream fo = new FileOutputStream(destPath);

        FileChannel inChannel = fi.getChannel();
        FileChannel outChannel = fo.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(16384);
        while (true) {
            buffer.clear();
            int r = inChannel.read(buffer);
            if (r == -1) {
                break;
            }
            buffer.flip();
            outChannel.write(buffer);
        }
    }

    public void ioCopyFile(String sourcePath, String destPath) throws IOException {
        FileInputStream fi = new FileInputStream(sourcePath);
        FileOutputStream fo = new FileOutputStream(destPath);
        byte b[] = new byte[16384];
        while (fi.read(b) != -1) {
            fo.write(b);
        }
        fi.close();
        fo.close();

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值