Java 無原生 USB 事件通知,常見做法是定期輪詢 File.listRoots() 或嘗試存取磁碟機代碼(C:~J:)。本文提供一個簡單的 CheckU 類別,每 5 秒掃描一次,偵測新磁碟機出現並通知。
import java.io.File;
import java.util.*;
public class USBDetector {
private static final String[] DRIVES = {"C","D","E","F","G","H","I","J"};
private static final Map state = new LinkedHashMap<>();
public static void main(String[] args) {
init();
detect();
}
private static void init() {
for (String d : DRIVES) {
state.put(d, new File(d + ":\\").exists());
}
}
private static void detect() {
while (true) {
for (String d : DRIVES) {
File root = new File(d + ":\\");
boolean now = root.exists();
if (now && !state.get(d)) {
System.out.println("偵測到新裝置: " + d + ":\\");
// 這裡可觸發業務邏輯
}
if (now != state.get(d)) state.put(d, now);
}
try { Thread.sleep(5000); } catch (InterruptedException ignored) {}
}
}
}
/media、/mnt,需調整掃描路徑。WM_DEVICECHANGE、Linux udev)。