获取驱动器根列表后,Java中是否有跨平台的方法来检查是否有任何驱动器:
我希望用户能够选择要播放的 DVD,并且将选项范围缩小到 DVD 驱动器而不是包括其他驱动器(例如笔式驱动器、硬盘驱动器等)在这种情况下会很有帮助。如果我可以获得此类驱动器的列表,显示哪些驱动器包含磁盘将再次有所帮助(同样的原因。)
在四处搜寻之后,我还没有找到任何不涉及特定于平台的黑客攻击的方法。外面有什么吗?
文件系统 API 可以做到这一点:
FileSystem fs = FileSystems.getDefault();
for (Path rootPath : fs.getRootDirectories())
{
try
{
FileStore store = Files.getFileStore(rootPath);
System.out.println(rootPath + ": " + store.type());
}
catch (IOException e)
{
System.out.println(rootPath + ": " + "<error getting store details>");
}
}
在我的系统上,它给出了以下内容(驱动器 D 中有一张 CD,其余硬盘或网络共享):
C:\: NTFS
D:\: CDFS
H:\: NTFS
M:\: NTFS
S:\: NTFS
T:\: NTFS
V:\: <error getting store details>
W:\: NTFS
Z:\: NTFS
因此对文件存储的
type() 进行查询应该可以做到这一点。
如果驱动器中没有 CD,则 getFileStore() 调用会抛出异常
java.nio.file.FileSystemException: D:: 设备尚未准备好。
FileSystem fs = FileSystems.getDefault();
for (FileStore store : fs.getFileStores()) {
String storeString = store.toString();
String type = store.type();
if (type.equals("tmpfs")) {
continue;
}
if (storeString.startsWith("/dev")) {
continue;
} else if (storeString.startsWith("/proc")) {
continue;
} else if (storeString.startsWith("/sys")) {
continue;
} else if (storeString.startsWith("/run/") && !storeString.startsWith("/run/user")) {
continue;
}
int index = storeString.indexOf(" (");
if (index < 0) {
continue;
}
String path = storeString.substring(0, index);
System.out.printf("%-30s %-20s %-10s\n", path, store.name(), type);
}
它只能检测*磁盘*,而不是驱动器。如果没有插入磁盘或磁盘损坏,安装点就会消失。
/ /dev/sda5 btrfs
/boot/efi /dev/sda1 vfat
/mnt/oldubuntu /dev/sda3 ext4
/home /dev/sda4 ext4
/run/user/1000/gvfs gvfsd-fuse fuse.gvfsd-fuse
/run/user/1000/doc portal fuse.portal
/media/zom-b/W1200A /dev/sdb1 ext4
/mnt/nasu [email protected]:/ fuse.sshfs
/media/zom-b/MovieDataDVD001 /dev/sr0 iso9660