Java实现文件复制的方法集

1.Java IO

public void JavaCopyFile(){
    //1.创建一个字节输入流对象,构造方法中绑定要读取的数据源
    File source = new File("D:/copy.txt");
    //2.创建一个字节输出流对象,构造方法中绑定要写入的目的地
    File target = new File("D:/Download/javaIO.txt");
    InputStream is = null;
    OutputStream os = null;
    try {
        is = new FileInputStream(source);
        os = new FileOutputStream(target);
        //3.使用数组缓冲读取多个字节,写入多个字节
        byte[] b = new byte[1024];
        int n = 0;
        while ((n = is.read(b)) != -1) {
            //4.使用字节输出流中的方法write,把读取到的字节写入到目的地的文件中
            os.write(b, 0, n);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //5.关闭流
        try {
            is.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2.FileChannel

public void JavaCopyFile(){
    File source = new File("D:/copy.txt");
    File target = new File("D:/Download/FileChannel.txt");
    FileChannel input = null;
    FileChannel output = null;
    try {
        input = new FileInputStream(source).getChannel();
        output = new FileOutputStream(target).getChannel();
        output.transferFrom(input, 0, input.size());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            input.close();
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3.Commons IO组件

FileUtils.copyFile(Source , Target);

public void JavaCopyFile() throws IOException {
    File source = new File("D:/copy.txt");
    File target = new File("D:/Download/CommonsIO.txt");
    FileUtils.copyFile(source, target);
}

4.Java7的Files类

public void JavaCopyFile() throws IOException {
    File source = new File("D:/copy.txt");
    File target = new File("D:/Download/Files.txt");
    Files.copy(source.toPath(), target.toPath());
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值