使用文件.listFiles()在Ubuntu中检测Java pendrive
我使用一个线程来检查pendrive是否已关闭,在两种状态之间切换为空/就绪使用文件.listFiles()在Ubuntu中检测Java pendrive,java,ubuntu,usb-drive,Java,Ubuntu,Usb Drive,我使用一个线程来检查pendrive是否已关闭,在两种状态之间切换为空/就绪 @Override public void run() { running = true; while(running){ // forever try { Delay.of_1second(); drivePath = getDrivePath(rootPath); if (isReady() &&
@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;
}
它在Windows中使用rootPath=“E:\”运行得很好,但在Ubuntu rootPath=“/media/Ubuntu”中不起作用,奇怪的是,我仍然不明白,如果我在文件管理器中打开pendrive,线程工作得很好,但我需要它在pendrive插入usb端口后立即工作,当用户使用“文件管理器”浏览文件时,则不会。我能做什么?在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驱动器的连接。< / P>谢谢你的回答,但是一旦我知道钢笔被插上了(用你的建议),我如何使用文件=新文件(“路径到笔”)访问它。在我用文件管理器浏览pendrive之前,这是不起作用的