JAVA批量重新命名
阿新 • • 發佈:2018-12-16
起因
原檔名太過於冗長,而且看起來肥腸的不爽,於是就想把它改掉!!!
改完之後,現在這樣就爽多了!!!
程式碼
import java.io.File; public class FileReName { public static void main(String[] args) { String[] fileName =getFileName("F:\\專案視訊\\04 JAVA學習\\03 動力結點王勇DRP視訊\\視訊"); for (int i = 30; i <fileName.length ; i++) { //-------------這裡是你想要對舊名字進行的操作,這裡我只是做了一個簡單的擷取--------------- String newName =fileName[i].substring(4);//修改新名字為從第四個字元之後的內容 //------------------------------------------------------------------------------- renameFile("F:\\專案視訊\\04 JAVA學習\\03 動力結點王勇DRP視訊\\視訊", fileName[i],newName); } System.out.println("OK"); } //得到檔名列表 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("新檔名和舊檔名相同..."); } } }
寫在最後
想到什麼就去試試看,可以做出很多好玩兒的小東西,另外程式碼非原創,有刪改,要學習的是這程式碼裡面的思想