前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >有一个文件夹下有很多的文件,每一个文件上都有年月日时,现在要根据这个年月日时创建文件夹,并且将这些文件迁移到对应的文件夹下,如何处理

有一个文件夹下有很多的文件,每一个文件上都有年月日时,现在要根据这个年月日时创建文件夹,并且将这些文件迁移到对应的文件夹下,如何处理

作者头像
一写代码就开心
发布2023-12-01 10:25:23
1550
发布2023-12-01 10:25:23
举报
文章被收录于专栏:java和python

1 问题

有一个文件夹下有很多的文件,每一个文件上都有年月日时,现在要根据这个年月日时创建文件夹,并且将这些文件迁移到对应的文件夹下,如何处理

Java 遍历一个文件夹,获取到后缀是tar.gz 的压缩包文件,压缩包的名称是TR_2023060200.tar.gz,然后获取到2023060200这个格式的,在当前目录下生成这个时间文件夹,然后将对应的压缩包迁移进去这个新建的时间文件夹

2 实现

代码语言:javascript
复制
public static void main(String[] args) {
        //File file = new File("D:\\059\\data\\RAIN_GRIB");
        String folderPath = "D:\\source"; // 文件夹路径
        File folder = new File(folderPath);
        File[] files = folder.listFiles();

        if (files != null) {
            for (File file : files) {
                if (file.isFile() && file.getName().endsWith(".tar.gz")) {
                    String fileName = file.getName();
                    String[] parts = file.getName().split("\\.");
                    String datePart = parts[0].substring(parts[0].lastIndexOf("_") + 1);
                    if (parts.length == 2) {

                        //String dateStr = parts[1].substring(0, parts[1].lastIndexOf("."));
                        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHH");
                        try {
                            Date date = format.parse(datePart);
                            String newFolderPath = folderPath + File.separator + datePart;
                            File newFolder = new File(newFolderPath);
                            if (!newFolder.exists()) {
                                newFolder.mkdir();
                            }
                            Path source = file.toPath();
                            Path destination = newFolder.toPath().resolve(fileName);
                            Files.move(source, destination, StandardCopyOption.REPLACE_EXISTING);
                            System.out.println("Moved file: " + fileName + " to folder: " + newFolderPath);
                        } catch (ParseException | IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-11-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1 问题
  • 2 实现
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档