Java implementation of listening u disk sample sharing
- 2020-04-01 03:10:01
- OfStack
package org.load.u;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;
//U disk test
public class CheckU {
//Storage disk status
private static Map<String, Boolean> map = new LinkedHashMap<String, Boolean>();
//Define the 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(" detected U disc ");
System.out.println(map);
}
//A dead loop detects each disk state
public static void check() {
File file ;
for(;;) {
for(String str : arr) {
file = new File(str + ":\");
//If the disk exists now and did not exist before
//Just plugged in and returned
if(file.exists() && !map.get(str)) {
return;
}
//The saved state needs to be updated each time the state changes
//If the state just detected is different from the original state, the state is reupdated
//You must put it under the if statement above
if(file.exists() != map.get(str)) {
map.put(str, file.exists());
}
}
try {
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//Initializes the disk state with true or false
public static void init() {
File file ;
for(String str : arr) {
file = new File(str + ":\");
map.put(str, file.exists());
}
}
}