The code copy is as follows:
package org.load.u;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;
// USB drive detection
public class CheckU {
//Storage disk status
private static Map<String, Boolean> map = new LinkedHashMap<String, Boolean>();
// Define disk
private static final String[] arr = new String[] {"C", "D", "E", "F", "G", "H", "I", "J"};
public static void main(String[] args){
init();
check();
System.out.println("U disk detected");
System.out.println(map);
}
// Deadly loop to detect the status of each disk
public static void check() {
File file;
for(;;) {
for(String str : arr) {
file = new File(str + "://");
// If the disk exists now and does not exist before
// It means that the USB drive has just been plugged in and returns
if(file.exists() && !map.get(str)) {
return;
}
// Every time the state changes, the saved state needs to be updated
// If the status just detected is different from the original state, then the status is updated
// You must put the above if statement below
if(file.exists() != map.get(str)) {
map.put(str, file.exists());
}
}
try {
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// Initialize disk status, true exists, otherwise false
public static void init() {
File file;
for(String str : arr) {
file = new File(str + "://");
map.put(str, file.exists());
}
}
}