針對下載視頻教程檔名過長(含機構廣告)、課件資料夾層級過深難以歸檔等痛點,基於 Java Swing 開發桌面工具,核心功能:
// TestFrame.java
public class TestFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new ShowGui().setVisible(true));
}
}
// ShowGui.java:使用 BoxLayout/FlowLayout 構建雙功能面板
// 6 個 JTextField 輸入路徑/關鍵字/類型,6 個 JButton 觸發操作
// 背景圖片由 BgSet 類透過 LayeredPane 實現
// RenameFunction.sure(sourceDir, keyword, replacement)
public static void sure(String dir, String keyword, String replacement) {
File file = new File(dir);
String[] names = file.list(); // 獲取原始檔名陣列(供撤銷用)
test1 = names; // 靜態變量備份
File[] files = file.listFiles();
for (int i = 0; i < names.length; i++) {
if (names[i].contains(keyword)) {
names[i] = names[i].replace(keyword, replacement);
}
}
// 實際重命名:遍歷 File 陣列對應修改
for (File f : files) {
if (f.isFile()) {
f.renameTo(new File(dir + "/" + names[i++]));
}
}
}
// RevokeRename.revoke(dir) 將 test1 備份的原始檔名恢復
public static void startCopy(String srcPath, String targetPath, String fileType) {
xunHuan(srcPath, targetPath, fileType);
}
private static void xunHuan(String current, String target, String type) {
File file = new File(current);
if (file.isFile() && file.getAbsolutePath().endsWith(type)) {
// 目標文件存在則重命名:檔名.擴展名 → 檔名{count}.擴展名
String dest = target + "/" + file.getName();
File destFile = new File(dest);
if (destFile.exists()) {
String[] parts = dest.split("\\."); // 注意轉義點號
dest = parts[0] + (count++) + "." + parts[1];
}
fileCopyByBufferStreamArray(file.getAbsolutePath(), dest);
} else if (file.isDirectory()) {
// 遞歸掃描子目錄
for (String name : file.list()) {
xunHuan(file.getAbsolutePath() + "/" + name, target, type);
}
}
}
// 緩衝流複製:10 bytes 緩衝區(示例用,生產建議 8KB+)
public static void fileCopyByBufferStreamArray(String src, String dest) { ... }
public static void startDelete(String targetPath) {
deleteFile(new File(targetPath));
}
private static void deleteFile(File file) {
if (file.isFile()) file.delete();
else if (file.isDirectory()) {
for (File f : file.listFiles()) deleteFile(f); // 遞歸刪除,保留目標資料夾本身
}
}
| 模組 | 核心 API | 注意事項 |
|---|---|---|
| GUI 佈局 | FlowLayout, BoxLayout, LayeredPane | 空佈局需手動 setBounds;背景圖片用 JLabel + LayeredPane 最底層 |
| 文件操作 | File.list(), listFiles(), renameTo() | renameTo 跨分區可能失敗;建議改用 Files.move(StandardCopyOption.REPLACE_EXISTING) |
| 流複製 | BufferedInputStream/OutputStream | 緩衝區過小(10B)效率極低,實際應用建議 8192 bytes |
| 撤銷機制 | 靜態變量備份原始檔名陣列 | 單例模式下靜態變量共享,多線程或多次操作會串擾,需改為實例變量+會話管理 |
java.nio.file (Java 7+) 替代舊 IO API,支援符號鏈接、屬性讀取、原子移動。ExecutorService)並行處理文件複製,顯示進度條。本工具展示了 Java Swing 開發桌面應用的完整流程:GUI 構建、事件監聽、文件遞歸遍歷、流式複製、狀態備份撤銷。雖然代碼存在硬編碼佈局、緩衝區過小、靜態變量共享等問題,但作為入門級文件處理工具的教學案例極具參考價值。