下載的劇集/文件名包含網站水印、亂碼前綴(如 `https://xxx_第1集.mp4`),需批量清洗為規範名稱(`甄嬛傳_第1集.mp4`)。
package gaiming;
import java.io.File;
import java.util.Scanner;
public class GaiMing {
public void gai() {
System.out.println("請輸入目標目錄路徑:");
Scanner input = new Scanner(System.in);
File dir = new File(input.nextLine());
File[] files = dir.listFiles();
if (files == null) {
System.out.println("目錄為空或不存在");
return;
}
System.out.println("請輸入要替換的公共字符(如水印前綴):");
String oldStr = input.nextLine();
System.out.println("請輸入替換後的字符(如劇名):");
String newStr = input.nextLine();
int count = 0;
for (File file : files) {
String path = file.getAbsolutePath();
if (path.contains(oldStr)) {
String newPath = path.replace(oldStr, newStr);
File newFile = new File(newPath);
if (file.renameTo(newFile)) {
System.out.println("重命名:" + file.getName() + " → " + newFile.getName());
count++;
} else {
System.err.println("失敗:" + file.getName() + "(可能目標已存在或無權限)");
}
}
}
System.out.println("完成,共重命名 " + count + " 個文件。");
}
public static void main(String[] args) {
new GaiMing().gai();
}
}
| 需求 | 實現思路 |
|---|---|
| 正則表達式替換 | `path.replaceAll(regex, replacement)` |
| 遞歸處理子目錄 | `Files.walkFileTree()` 或遞歸 `listFiles()` |
| 預覽模式 | 先收集重命名映射表,確認後再執行 |
| 撤銷功能 | 記錄操作日誌(原名→新名),支持回滾 |
| 圖形界面 | Swing/JavaFX 拖拽目錄、預覽列表、一鍵執行 |
請輸入目標目錄路徑:
D:\Downloads\ZhenHuan
請輸入要替換的公共字符:
https://isoivjsvlkfdjorwiu pijklsjvgoij ;lkjioju
請輸入替換後的字符:
甄嬛傳
重命名:https://isoivjsvlkfdjorwiu pijklsjvgoij ;lkjioju第1集.mp4 → 甄嬛傳第1集.mp4
重命名:https://isoivjsvlkfdjorwiu pijklsjvgoij ;lkjioju第2集.mp4 → 甄嬛傳第2集.mp4
...
完成,共重命名 72 個文件。