自己使用的代码片段积累(文件操作)

自己使用的代码片段积累

  • 批量修改 xxx 文件(具体需求自己定制,代码示例为批量修改文件名)
/**
     * 批量修改文件名(替换、删除文件或者移动文件)
     * 当前为一个批量修改文件名的小 Demo
     *
     * @param dirPath
     * @throws Exception
     */
    public static void batchRenameFiles(String dirPath) throws Exception {
        File file = new File(dirPath);
        //如果 File 存在且是一个目录
        if (file.exists() && file.isDirectory()) {
            //获取目录下所有文件
            File[] listFiles = file.listFiles();
            if (listFiles == null || listFiles.length < 1) {
                throw new Exception(">>>>>> 当前目录 " + file.getCanonicalPath() + "为空!");
            }
            //遍历 List (文件和子目录分别处理)
            for (File fileItem : listFiles) {
                //包含子目录
                if (fileItem.isDirectory()) {
                    System.out.println(">>>>>> " + fileItem.getCanonicalPath() + " 为一个子目录,继续递归.....");
                    batchRenameFiles(fileItem.getCanonicalPath());
                } else {
                    //rename 的具体需求(批量删除、替换或者移动文件都可以看具体需求) eg:替换.txt 文件为 .log 文件
                    String oldFileName = fileItem.getName();
                    if (oldFileName.endsWith(".txt")) {
                        String newFileName = fileItem.getParentFile().getCanonicalPath() + File.separator + oldFileName
                            .substring(0, oldFileName.lastIndexOf(".")) + ".log";
                        boolean renameTo = fileItem.renameTo(new File(newFileName));
                        if (renameTo) {
                            System.out.println(">>>>>> 重新命名后的文件名为:" + newFileName);
                        }
                    }
                }
            }
        }
    }
posted @ 2020-12-16 23:12  东街浊酒づ  阅读(76)  评论(0编辑  收藏  举报