JAVA實現本地檔案批量重新命名
阿新 • • 發佈:2019-02-02
專案中需要使用大量的網路圖片,但是下載下來的圖片命名不一致,導致專案呼叫很麻煩,Windows雖然提供了重新命名工具,但是重新命名後的檔案帶有(*)符號,在專案中報錯,故自己寫了一個JAVA程式,來輔助完成程式的重新命名工作。
package ny; import java.io.File; public class GetFileName { public static String [] getFileName(String path) { File file = new File(path); String [] fileName = file.list(); return fileName; } public static void renameFile(String path,String oldname,String newname){ if(!oldname.equals(newname)){//新的檔名和以前檔名不同時,才有必要進行重新命名 File oldfile=new File(path+"\\"+oldname); File newfile=new File(path+"\\"+newname); if(!oldfile.exists()){ return;//重新命名檔案不存在 } if(newfile.exists())//若在該目錄下已經有一個檔案和新檔名相同,則不允許重新命名 System.out.println(newname+"已經存在!"); else{ oldfile.renameTo(newfile); } }else{ System.out.println("新檔名和舊檔名相同..."); } } public static void main(String[] args) { String [] fileName = getFileName("C:\\Users\\Administrator\\Desktop\\Img");//<span style="font-family: Arial, Helvetica, sans-serif;">此處修改為你的本地路徑</span> for (int i = 0; i < fileName.length; i++) { renameFile("C:\\Users\\Administrator\\Desktop\\Img", fileName[i], "cx"+i+".jpg");//cx修改為你要修改的檔名格式 } } }