使用 Java 重新命名多個檔案


以下是使用 Java 重新命名多個檔案的程式碼 −

示例

import java.io.File;
import java.io.IOException;
public class Demo{
   public static void main(String[] argv) throws IOException{
      String path_to_folder = "path\to\folder\where\multiple\files\are\present";
      File my_folder = new File(path_to_folder);
      File[] array_file = my_folder.listFiles();
      for (int i = 0; i < array_file.length; i++){
         if (array_file[i].isFile()){
            File my_file = new File(path_to_folder + "\" + array_file[i].getName());
            String long_file_name = array_file[i].getName();
            String[] my_token = long_file_name.split("\s");
            String new_file = my_token[1];
            System.out.println(long_file_name);
            System.out.print(new_file);
            my_file.renameTo(new File(path_to_folder + "\" + new_file + ".pdf"));
         }
      }
   }
}

輸出

The files in the folder will be renamed to .pdf

一個名為 Demo 的類包含 main 函式,其中定義了包含多個檔案的檔案路徑。在提到的路徑中建立一個新資料夾。

使用 'listFiles' 函式獲取檔案列表。遍歷檔案陣列,如果遇到檔案,則建立一個新的檔案路徑,並獲取檔名並將其拆分。將檔案重新命名為 .pdf。透過獲取在 'long_file_name' 中第一個空格之後開始的子字串來縮短檔名稱。

更新於: 04-Jul-2020

1K+ 瀏覽

啟動你的 職業生涯

完成課程以獲得認證

開始
廣告