Java遍歷文件夾下所有文件並重新命名

項目中需要將一批文件全部重新命名,文件實在太多就寫了這個工具類

這個工具類是將路徑下的文件全部重新命名,且名字爲同一個

package com.xingli.FileDemo;

import java.io.File;

/**
 *@ClassName FileDemo
 *@Description TODO
 *@Author William
 *@Date 2019/8/8 14:51
 *@Version 1.0
 */
public class FileDemo {

    public static void main(String[] args) {
        changeFileName("D:\\paper");
    }

    /**
     *@description: 通過文件路徑,修改該路徑下所有文件的名字
     * @param path  文件夾路徑
     * @return:
     * @author: William
     * @date 2019/8/8 14:52
     */
    public static void changeFileName(String path){
       File file = new File(path);
       if(file.exists()){
           File[] files = file.listFiles();
           if (null == files || files.length == 0) {
               System.out.println("文件夾是空的!");
               return;
           } else {
               for (File file2 : files) {
                   if (file2.isDirectory()) {
                       changeFileName(file2.getAbsolutePath());
                   } else {
                       System.out.println("文件:" + file2.getAbsolutePath());
                       String filePath = file2.getAbsolutePath();
                       String fileName = filePath.substring(0,filePath.lastIndexOf("\\"))+"\\aaa"+filePath.substring(filePath.lastIndexOf("."));
                       File oriFile = new File(filePath);
                       boolean b = oriFile.renameTo(new File(fileName));
                       System.out.println(b);
                   }
               }
           }
       }else{
           System.out.println("該路徑不存在");
       }

    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章