递归查找指定目录中(包括子目录中),所有的.java文件, 并且,把所有这些找到的java文件,复制到一个指定的目录下。

6/26
递归查找指定目录中(包括子目录中),所有的.java文件,
并且,把所有这些找到的java文件,复制到一个指定的目录下。
注意:复制文件包括文件内容

public class Work02 {
    public static void main(String[] args) {

        File sourceDir = new File("D:\\JAVAlearning\\firstLevel");
        File file = new File("d:\\JAVAlearning\\JAVA");
        file.mkdirs();
        String targetDir = "d:\\JAVAlearning\\JAVA\\";
        eachFile(sourceDir);
        //复制所有.java文件到目标文件夹
        for (int i = 0; i < files.size(); i++) {
            FileInputStream input = null;
            FileOutputStream output = null;
            try {
                input = new FileInputStream(files.get(i));
                InputStream inbuffer = new BufferedInputStream(input);
                //目标文件由输出流自己创建
                output = new FileOutputStream(targetDir + files.get(i).getName());
                OutputStream outbuffer = new BufferedOutputStream(output);
                //利用字节缓冲流复制文件
                byte[] b = new byte[1024];
                int len;
                while ((len = inbuffer.read(b)) != -1) {
                    outbuffer.write(b, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                closeQuietly(input);
                closeQuietly(output);
            }

        }
    }

    public static void closeQuietly(Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static ArrayList<File> files = new ArrayList<>();

    //遍历这个文件夹内的所有子目录和文件
    public static void eachFile(File file) {
        try {
            File[] tagetFile = file.listFiles();
            for (int i = 0; i < tagetFile.length; i++) {
                if (tagetFile[i].isDirectory()) {
                    eachFile(tagetFile[i]);
                } else {
                    //找到所有.java文件并且放到集合中
                    if (tagetFile[i].getName().endsWith(".java")) {
                        files.add(tagetFile[i]);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LxyrichBos

老板~坐下喝杯茶啊~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值