JAVA监控windows7系统的USB插拔事件

package com.wiscom.ism.usb.services;

import com.wiscom.ism.common.pojo.EnumObject;
import com.wiscom.ism.usb.dao.CfgDictionaryMapper;
import com.wiscom.ism.usb.dao.UsbEventMapper;
import com.wiscom.ism.usb.pojo.CfgDictionary;
import com.wiscom.ism.usb.pojo.CurrencyEventEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service("UsbSerivice")
public class UsbSeriviceImp implements UsbSerivice {

    private static Logger logger = LoggerFactory.getLogger(UsbSeriviceImp.class);


    File[] root = File.listRoots();

    Runnable myRunnable = () -> {
        System.out.println("扫描系统...");
        while (true) {
            File[] files = File.listRoots();
            if (files.length > root.length) {
                root = File.listRoots();
                logger.error("有U盘插入");
            } else if (files.length < root.length) {
                root = File.listRoots();
                logger.error("有U盘拔出");
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };

    Thread thread = new Thread(myRunnable);
    //启动监控线程
    public void startUsbService() {
        thread.start();
    }

}
原文地址:https://www.cnblogs.com/maocai2018/p/9938629.html