IO流实践:在windows上批量复制文件

在windows上批量复制文件

在windows上从不同文件夹中复制作业卷到同一个文件夹。虽然可以使用windows的搜索功能进行搜索并复制,但是作业卷的名称都叫‘每日作业卷’,无法对其内容进行区分,想复制并添加文件前缀需要多步操作。

需求

从每天的资料文件中收集每天作业卷,并添加前缀放到特定的文件夹里面,实现作业卷的批量复制。

分析

通过遍历源文件目录,取得文件名,通过正则表达式过滤得到所需文件。对文件取名。通过IO流复制文件。

public class CollectHomeWork {

    //复制文件的源文件目录
    private static String resourcePath = "C:\\Users\\zmysna\\Desktop\\基础班学生软件";
    //复制文件的目标目录
    private static String copyPath = "C:\\Users\\zmysna\\Desktop\\基础班学生软件\\作业收集\\";
    //正则表达式过滤文件名
    private static String regex = ".*每日作业卷.*";

    public static void main(String[] args) {
        File rootDir = new File(resourcePath);
        layerOrder(rootDir);
    }

    /**
     * 遍历文件夹,将查询所有的作业卷。
     * 将它们复制到特定文件夹中。
     *
     * @param rootDir 目录名
     */
    private static void layerOrder(File rootDir) {
        LinkedList<File> queue = new LinkedList<>();
        queue.add(rootDir);
        while (!queue.isEmpty()) {
            File file = queue.removeFirst();
            //如果是目录,把它的所有子文件加入队列
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                queue.addAll(Arrays.asList(files));
            } else {
                String name = file.getName().split("\\.")[0];
                Pattern p = Pattern.compile(regex);
                Matcher matcher = p.matcher(name);
                if (matcher.find()) {
                    copyFileToMyDir(file);
                }
            }
        }
    }

    /**
     * 复制文件到特定的文件夹
     *
     * @param file
     */
    private static void copyFileToMyDir(File file) {
        String prefix = getName(file);
        try (
                BufferedInputStream br = new BufferedInputStream(new FileInputStream(file));
                BufferedOutputStream bw = new BufferedOutputStream(new FileOutputStream(copyPath + prefix ));
        ) {
            byte[] content = new byte[512];
            int len = 0;
            while ((len = br.read(content)) != -1) {
                bw.write(content, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 为复制的文件取名。
     */
    private static String getName(File file) {
        File parent = file.getParentFile();
        while (!parent.getName().contains("day")) {
            parent = file.getParentFile();
        }
        String prefix = parent.getName().substring(0, 5);
        prefix += "每日作业卷.pdf";
        return prefix;
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值