1. 程式人生 > >java實現讀取檔案底下所有子檔名,並修改檔名

java實現讀取檔案底下所有子檔名,並修改檔名

作為班上的學委,一學期到頭經常要收班級各種各樣的文件、實驗報告,這些實驗報告還需要統一命名,有些老師會一開始就給出命名格式,但是也有的會沒給,然後等我按照自己規定的格式收齊了作業之後,老師又丟擲一個格式說必須要按他那樣……例如我這次就遇到了這種情況,四次實驗,加起來近140份檔案,要一份份的改,當然是不可能的了,效率太低,不符合程式設計師的做事風格,於是就決定自己敲個程式來讓電腦幫我做!接下來就看程式碼吧!

 public   static   void   main(String[]   args)   {
		 File file=new File("C:\\Users\\CMS\\Desktop\\網路管理實驗\\實驗二");  //實驗報告存放路徑
		 String [] fileName = file.list();  //用於存放檔案底下所有子檔名的陣列
		 int beginIndex=0;   
		 int endIndex=0;
		 String[] studentName=new String[fileName.length];//用於儲存提取出來的姓名的陣列
		 String[] studentId=new String[fileName.length];//用於儲存提取出來的學號的陣列
		 //先提取原檔名中有效的資訊
		 for (int i = 0; i < fileName.length; i++) {
			 beginIndex=fileName[i].indexOf("_")+1;  //根據原先的命名格式匹配出想要的資訊(具體根據你們自己的情況咯!)
			 endIndex=fileName[i].lastIndexOf("_");
			 studentName[i]=fileName[i].substring(beginIndex, endIndex);//這是我這邊學生姓名的範圍
			 studentId[i]=fileName[i].substring(0, 10);//這是學號的範圍
		}
		 //開始重新命名
		for(int i=0;i<fileName.length;i++){
			 File toBeRenamed = new File("C:\\Users\\CMS\\Desktop\\網路管理實驗\\實驗二\\"+fileName[i]);
		     //檢查要重新命名的檔案是否存在
		     if (!toBeRenamed.exists()) {
		         System.out.println("File does not exist: "+i);
		         return;
		     }
		   //修改檔名
		     File newFile = new File("C:\\Users\\CMS\\Desktop\\網路管理實驗\\實驗二\\實驗二(2014級+"+studentId[i]+"+"+studentName[i]+").docx");
		     if (toBeRenamed.renameTo(newFile)) {
		          System.out.println("File renamed success!!.");
		     } else {
		          System.out.println("Error renmaing file");
		     }
		}
	     
	 }