实现文件拷贝

方法一: 单字节逐一拷贝

public class TestDemo {
    public static void main(String [] args) throws IOException {
        // 将文件的源和目的位置初始化到file数组中
        String [] str = {"F:\\demo\\demo.txt","F:\\demo\\Demo1.txt"};
        if (str.length != 2) {
            System.out.println("命令执行错误");
            System.exit(1);// 退出程序
        }
        File inFile = new File(str[0]); // 源文件
        if(!inFile.exists()) { //源文件是否存在
            System.out.println("源文件不存在");
            System.exit(1);
        }
        File outFile = new File(str[1]);
        if (!outFile.getParentFile().exists()) { // 目的是否存在
            outFile.getParentFile().mkdirs(); //创建目录以及文件
        }
        InputStream input = new FileInputStream(inFile);
        OutputStream output = new FileOutputStream(outFile);
        // 完成两个文件的实例对象
        int temp = 0 ; //保存读取的内容
        while ((temp = input.read()) != -1) { // 每次读取单个字节,输出到目标文件中
            output.write(temp);
        }
        input.close();
        output.close();
    }   
}
  • 遇到大容量的文件时,拷贝速度非常慢!!!
    ****

    方法二:部分数据拷贝

public class TestDemo {
    public static void main(String [] args) throws IOException {
        // 将文件的源和目的位置初始化到file数组中
        String [] str = {"F:\\demo\\demo.txt","F:\\demo\\Demo1.txt"};
        if (str.length != 2) {
            System.out.println("命令执行错误");
            System.exit(1);// 退出程序
        }
        File inFile = new File(str[0]); // 源文件
        if(!inFile.exists()) { //源文件是否存在
            System.out.println("源文件不存在");
            System.exit(1);
        }
        File outFile = new File(str[1]);
        if (!outFile.getParentFile().exists()) { // 目的是否存在
            outFile.getParentFile().mkdirs(); //创建目录以及文件
        }
        InputStream input = new FileInputStream(inFile);
        OutputStream output = new FileOutputStream(outFile);
        // 完成两个文件的实例对象
        int temp = 0 ; //保存读取的内容
        byte [] data = new byte[1024]; // 每次读取1024字节
        while ((temp = input.read(data)) != -1) { // 每次读取单个字节,输出到目标文件中
            output.write(data,0,temp);
        }
        input.close();
        output.close();
    }
}

转载于:https://www.cnblogs.com/wangyuyang1016/p/11160333.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值