查找并拷贝目录中指定文件到某个文件夹

  说明:该方法是通过递归遍历的方式查找某个文件夹及其子文件夹中的所有文件,如果检测到是.jpg文件就将其复制到D:\Download\target中。

  需求场景:手机中有大量的文件,但是,我们只关心其中格式是.jpg的文件,因为它们记录了我生活的许多美好回忆。手动查找效率低,故考虑写一个程序,自动识别。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

public class BigOne {
    // 计数器,用于命名文件
    private static int id;

    public static void main(String[] args) {
        Long start = System.currentTimeMillis();
        String targetPath = "D:\\Download\\target";
        File dir = new File(targetPath);
        dir.mkdirs();//创建目录
        File source = new File("D:\\train照片副本\\image2");
        String fileType = ".jpg";
        search(source, targetPath, fileType);
        System.out.println("-----Done---------" + (System.currentTimeMillis() - start) + "文件数量:" + id);
        return;
    }

    public static void search(File source, String targetPath, String fileType) {
        File[] ds = null;
        if (source.isDirectory()) {
            ds = source.listFiles();
        }
        if (ds == null) {
            return;
        }
        System.out.println("ds长度=" + ds.length);
        List<File> js = new ArrayList();
        for (File aFile : source.listFiles()) {
            if (aFile.isFile() && aFile.getName().toLowerCase().endsWith(fileType)) {
                js.add(aFile);
            }
        }

        for (File j : js) {
            System.out.println(j);    //打印文件名
            String name = ++id + "";
            while (name.length() < 5) {
                name = "0" + name;
            }
            name += fileType; //创建一个File对象代表目标文件
            File t = new File(targetPath, name);//文件复制 源文件j 目标文件t
            try (FileInputStream fis = new FileInputStream(j);
                 FileOutputStream fos = new FileOutputStream(t)) {
                byte[] data = new byte[16384];//16k
                int len;
                while ((len = fis.read(data)) != -1) {
                    fos.write(data, 0, len);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        for (File d : ds) {
            search(d, targetPath, fileType);
        }
    }
}

Reference

posted @ 2021-05-31 21:28  楼兰胡杨  阅读(340)  评论(0编辑  收藏  举报