使用java获取驱动器信息时

我尝试了以下程序

import java.io.*; class dr { public static void main(String args[]) { try{ File[] roots = File.listRoots(); for (int index = 0; index < roots.length; index++) { //Print out each drive/partition System.out.println(roots[index].toString()); } } catch(Exception e) { System.out.println("error " +e); } } } 

但在我的系统软盘驱动器没有连接,我收到如下消息

“驱动器尚未准备好使用;它的门可能已打开,请检查驱动器A:并确保已插入磁盘并且驱动器门已关闭”然后显示三个选项取消,再次尝试,继续我尝试继续,它的工作原理,但我怎么能避免这个消息

你想做什么?

我的建议是使用FileSystemView 。

它使用了这样的东西:

 FileSystemView fsv = FileSystemView.getFileSystemView(); File[] roots = fsv.getRoots(); for (File f: roots) { System.out.println(fsv.getSystemDisplayName(f); } 
 package com.littletutorials.fs; import java.io.*; import javax.swing.filechooser.*; public class DriveTypeInfo { public static void main(String[] args) { System.out.println("File system roots returned byFileSystemView.getFileSystemView():"); FileSystemView fsv = FileSystemView.getFileSystemView(); File[] roots = fsv.getRoots(); for (int i = 0; i < roots.length; i++) { System.out.println("Root: " + roots[i]); } System.out.println("Home directory: " + fsv.getHomeDirectory()); System.out.println("File system roots returned by File.listRoots():"); File[] f = File.listRoots(); for (int i = 0; i < f.length; i++) { System.out.println("Drive: " + f[i]); System.out.println("Display name: " + fsv.getSystemDisplayName(f[i])); System.out.println("Is drive: " + fsv.isDrive(f[i])); System.out.println("Is floppy: " + fsv.isFloppyDrive(f[i])); System.out.println("Readable: " + f[i].canRead()); System.out.println("Writable: " + f[i].canWrite()); System.out.println("Total space: " + f[i].getTotalSpace()); System.out.println("Usable space: " + f[i].getUsableSpace()); } } 

}

参考: http : //littletutorials.com/2008/03/10/getting-file-system-details-in-java/

说到Windows,这个类WindowsAltFileSystemView提出了一个基于FileSystemView的替代方案

由于Windows NT上的一个恼人的错误,这个类是必要的,其中使用默认的FileSystemView实例化JFileChooser将导致每次都出现“ drive A: not ready ”错误。
我从1.3 SDK中获取了Windows FileSystemView impl并对其进行了修改,以便不使用java.io.File.listRoots()来获取fileSystem根目录。

java.io.File.listRoots()执行一个SecurityManager.checkRead() ,它导致操作系统尝试访问驱动器A:即使没有磁盘 ,每次我们实例化时都会导致恼人的“ abort, retry, ignore ”弹出消息一个JFileChooser

所以在这里,我们的想法是扩展FileSystemView ,将getRoots()方法替换为:

  /** * Returns all root partitians on this system. On Windows, this * will be the A: through Z: drives. */ public File[] getRoots() { Vector rootsVector = new Vector(); // Create the A: drive whether it is mounted or not FileSystemRoot floppy = new FileSystemRoot("A" + ":" + "\\"); rootsVector.addElement(floppy); // Run through all possible mount points and check // for their existance. for (char c = 'C'; c <= 'Z'; c++) { char device[] = {c, ':', '\\'}; String deviceName = new String(device); File deviceFile = new FileSystemRoot(deviceName); if (deviceFile != null && deviceFile.exists()) { rootsVector.addElement(deviceFile); } } File[] roots = new File[rootsVector.size()]; rootsVector.copyInto(roots); return roots; }