【问题标题】:Java detect pendrive in Ubuntu with file.listFiles()Java 使用 file.listFiles() 在 Ubuntu 中检测 pendrive
【发布时间】:2014-10-28 09:22:36
【问题描述】:

我正在使用线程来定期检查 pendrive 是否连接,在 EMPTY / READY 两种状态之间切换

@Override
public void run() {
    running = true;
    while(running){ // forever
        try {
            Delay.of_1second();
            drivePath = getDrivePath(rootPath);
            if (isReady() && drivePath==null){
                notifyNewState(DriveState.EMPTY);
            }
            else if (!isReady() && drivePath!=null){
                notifyNewState(DriveState.READY);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

private String getDrivePath(String rootPath){
    File file = new File(rootPath);
    if (SystemUtils.IS_OS_WINDOWS){
        return file.exists() ? rootPath : null;
    }
    else{
        for (File f : file.listFiles()){
            if (!f.getName().equalsIgnoreCase("CDROM")){
                return f.getAbsolutePath(); // we return the first folder other than 'CDROM'
            }
        }
    }
    return null;
}

它在具有 rootPath="E:\" 的 Windows 中工作得很好,但在 Ubuntu rootPath="/media/ubuntu" 中不起作用,我仍然不明白的奇怪点是 线程工作如果我在文件管理器中打开 pendrive 很好,但我需要它在 pendrive 插入 USB 端口后立即工作,而不是当用户使用文件管理器浏览文件时。我能做什么?

【问题讨论】:

    标签: java ubuntu usb-drive


    【解决方案1】:

    在 Linux 机器上,我能想到两个命令,它们可以为您提供有关插入哪些设备的有用信息。第一个是 lsusb。当我在我的机器上运行它时:

    Bus 002 Device 003: ID 8086:0189 Intel Corp. 
    Bus 002 Device 021: ID 0718:061a Imation Corp. 
    Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
    ...
    

    第二行是我的笔式驱动器。 另一个命令是 dmesg

    [148541.700254] sd 8:0:0:0: [sdb] Attached SCSI removable disk
    [148830.993250] usb 2-1.2: USB disconnect, device number 21
    [148836.316642] usb 2-1.2: new high-speed USB device number 22 using ehci-pci
    [148836.415145] usb 2-1.2: New USB device found, idVendor=..., idProduct=....
    [148836.415157] usb 2-1.2: New USB device strings: Mfr=1, Product=2, SerialNumber=3
    [148836.415162] usb 2-1.2: Product: iPhone
    [148836.415167] usb 2-1.2: Manufacturer: Apple Inc.
    [148836.415171] usb 2-1.2: SerialNumber: ....
    [148836.894819] ipheth 2-1.2:4.2: Apple iPhone USB Ethernet device attached
    

    您可以将程序设置为轮询这些命令中的任何一个并解析输出,即使用Runtime.getRuntime().exec("dmesg)"

    我认为这个解决方案是一种变通方法,我想还有很多其他可能的方法来检测 USB 驱动器何时连接。

    【讨论】:

    • 感谢您的回答,但是一旦我知道笔已插入(根据您的建议),我如何使用 File file = new File("path-to-pen");在我使用文件管理器浏览 pendrive 之前,这不起作用
    猜你喜欢
    • 2013-01-31
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 2013-02-04
    • 1970-01-01
    相关资源
    最近更新 更多