复制文件 以及复制文件夹

此博客记录了Java复制文件相关内容,虽未详细展开,但围绕Java语言实现文件复制这一信息技术操作。

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

笔记:

package Test;

import java.io.*;

public class 文件拷贝 {
    public static void main(String[] args) throws IOException {
        copyFile1("E:\\python.py", "E:\\test.txt"); // 字符数字复制文件
        copyFile2("E:\\python.py", "E:\\test.txt"); // 每次读一行复制文件
        copyFile3("E:\\Test", "D:\\test1"); // 复制文件夹
    }


    public static void copyFile1(String s1, String s2) throws IOException {
        InputStream is = null; // 源文件
        OutputStream os = null; // 目标文件
        //读一个字符数组的长度
        try {
            os = new FileOutputStream(new File(s2));
            is = new FileInputStream(new File(s1));
            byte[] b = new byte[1024 * 8];
            int i;
            while ((i = is.read(b)) != -1) {
                os.write(b, 0, b.length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            is.close();
            os.close();
        }
    }

    private static void copyFile2(String s1, String s2) {
        try {
            BufferedReader br = new BufferedReader(new FileReader(s1));// 源文件
            BufferedWriter bw = new BufferedWriter(new FileWriter(s2));// 目标文件
            String str = null;
            //每次读一行
            while ((str = br.readLine()) != null) {
                bw.write(str, 0, str.length());
            }
            br.close();
            bw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static void copyFile3(String oldPath, String newPath) {
        File file = new File(oldPath);
        String[] filePath = file.list();
        if (!(new File(newPath)).exists()) {
            (new File(newPath)).mkdir();
        }

        for (int i = 0; i < filePath.length; i++) {
            if ((new File(oldPath + File.separator + filePath[i])).isDirectory()) {
                copyFile3(oldPath  + File.separator  + filePath[i], newPath  + File.separator + filePath[i]);
            }

            if (new File(oldPath  + File.separator + filePath[i]).isFile()) {
                copyFile2(oldPath + File.separator + filePath[i], newPath + File.separator + filePath[i]);
            }

        }

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值