Java實現批量修改檔名和重新命名的方法
阿新 • • 發佈:2020-09-12
平時下載的檔案、視訊很多都會有網址字首,比如一些程式設計的教學視訊,被人共享出來後,所有視訊都加上一串長長的網址,看到就煩,所以一般會重新命名後看,舒服很多,好了,不多說,直接上程式碼:
以下程式碼演示使用遞迴的方式批量重新命名檔案
import java.io.File; import java.io.IOException; /** * @Auther: Code * @Date: 2018/9/9 18:02 * @Description: 批量重新命名檔案 */ public class test { static String newString = "";//新字串,如果是去掉字首字尾就留空,否則寫上需要替換的字串 static String oldString = "home.cnblogs.comu";//要被替換的字串 static String dir = "E:\檔案\學習\教程\實戰\test";//檔案所在路徑,所有檔案的根目錄,記得修改為你電腦上的檔案所在路徑 public static void main(String[] args) throws IOException { recursiveTraversalFolder(dir);//遞迴遍歷此路徑下所有資料夾 } /** * 遞迴遍歷資料夾獲取檔案 */ public static void recursiveTraversalFolder(String path) { File folder = new File(path); if (folder.exists()) { File[] fileArr = folder.listFiles(); if (null == fileArr || fileArr.length == 0) { System.out.println("資料夾是空的!"); return; } else { File newDir = null;//檔案所在資料夾路徑+新檔名 String newName = "";//新檔名 String fileName = null;//舊檔名 File parentPath = new File("");//檔案所在父級路徑 for (File file : fileArr) { if (file.isDirectory()) {//是資料夾,繼續遞迴,如果需要重新命名資料夾,這裡可以做處理 System.out.println("資料夾:" + file.getAbsolutePath() + ",繼續遞迴!"); recursiveTraversalFolder(file.getAbsolutePath()); } else {//是檔案,判斷是否需要重新命名 fileName = file.getName(); parentPath = file.getParentFile(); if (fileName.contains(oldString)) {//檔名包含需要被替換的字串 newName = fileName.replaceAll(oldString,newString);//新名字 newDir = new File(parentPath + "/" + newName);//檔案所在資料夾路徑+新檔名 file.renameTo(newDir);//重新命名 System.out.println("修改後:" + newDir); } } } } } else { System.out.println("檔案不存在!"); } } }
重新命名前效果圖:
test目錄:
test1目錄:以此類推,test3和test4都一樣的檔名
修改後效果圖:
控制檯輸出:
test目錄:
test1目錄:
到此這篇關於Java實現批量修改檔名和重新命名的方法的文章就介紹到這了,更多相關Java批量修改檔名重新命名內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!