Java 如何获取所有驱动器的列表,同时获取相应的驱动器类型(可移动、本地磁盘或 cd-rom、dvd-rom...等)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3542018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 01:42:26  来源:igfitidea点击:

How can I get list of all drives but also get the corresponding drive type (removable,local disk, or cd-rom,dvd-rom... etc)?

java

提问by xolmc

How can I get list all drives but also get the corresponding drive type (removable,local disk, or cd-rom,dvd-rom... etc)?

如何获取所有驱动器的列表,同时获取相应的驱动器类型(可移动、本地磁盘或 cd-rom、dvd-rom...等)?

回答by Borealid

There's no definition for what you're asking.

你问的问题没有定义。

I have a thumb drive which, when I plug it in, shows up as a CD-ROM. After I run a program on the CD-ROM it attaches a second partition which appears to be a hard drive.

我有一个拇指驱动器,当我插入它时,它显示为 CD-ROM。在我运行 CD-ROM 上的程序后,它附加了第二个分区,它似乎是一个硬盘驱动器。

I have removable CD-ROM drives. I also have "internal" eSATA hard drives on the outside of my computer.

我有可移动的 CD-ROM 驱动器。我的计算机外部也有“内部”eSATA 硬盘驱动器。

You'd have to work pretty hard to get a binding definition for the "type" of the drive. Why don't you tell us what you're trying to do, instead of asking about the particular way you want to do it?

您必须非常努力地获得驱动器“类型”的绑定定义。你为什么不告诉我们你想做什么,而不是询问你想要做的特定方式?

回答by Louis Rhys

Assuming it's windows, use File.listRoots()to get all roots. Then use FileSystemViewto check whether it's floppy disk or a drive. Other than that I have no idea.

假设它是窗口,用于File.listRoots()获取所有根。然后用FileSystemView它来检查它是软盘还是驱动器。除此之外我不知道。

回答by pafivi

With this code you can get all drives and its type description

使用此代码,您可以获得所有驱动器及其类型说明

File[] paths;
FileSystemView fsv = FileSystemView.getFileSystemView();

// returns pathnames for files and directory
paths = File.listRoots();

// for each pathname in pathname array
for(File path:paths)
{
    // prints file and directory paths
    System.out.println("Drive Name: "+path);
    System.out.println("Description: "+fsv.getSystemTypeDescription(path));
}

回答by Martin Vysny

If you use JACOB, you can list all drives along with appropriate types:

如果使用JACOB,则可以列出所有驱动器以及适当的类型:

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.EnumVariant;
import com.jacob.com.JacobObject;
import com.jacob.com.Variant;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class DrivesExample
{
    public interface HasNativeValue
    {
        int getNativeValue();
    }

    public enum DriveTypeEnum implements HasNativeValue
    {
        Unknown(0),
        NoRootDirectory(1),
        RemovableDisk(2),
        LocalDisk(3),
        NetworkDrive(4),
        CompactDisc(5),
        RAMDisk(6);

        public final int nativeValue;

        DriveTypeEnum(int nativeValue)
        {
            this.nativeValue = nativeValue;
        }

        public int getNativeValue()
        {
            return nativeValue;
        }
    }

    private static <T extends Enum<T> & HasNativeValue> T fromNative(Class<T> clazz, int value)
    {
        for (T c : clazz.getEnumConstants())
        {
            if (c.getNativeValue() == value)
            {
                return c;
            }
        }
        return null;
    }

    /**
     * The drive information.
     */
    public static final class Drive
    {
        /**
         * File system on the logical disk. Example: NTFS. null if not known.
         */
        public final String fileSystem;
        /**
         * Value that corresponds to the type of disk drive this logical disk represents.
         */
        public final DriveTypeEnum driveType;
        /**
         * The Java file, e.g. "C:\". Never null.
         */
        public final File file;

        public Drive(String fileSystem, DriveTypeEnum driveType, File file)
        {
            this.fileSystem = fileSystem;
            this.driveType = driveType;
            this.file = file;
        }

        @Override
        public String toString()
        {
            return "Drive{" + file + ": " + driveType + ", fileSystem=" + fileSystem + "}";
        }
    }

    /**
     * Lists all available Windows drives without actually touching them. This call should not block on cd-roms, floppies, network drives etc.
     *
     * @return a list of drives, never null, may be empty.
     */
    public static List<Drive> getDrives()
    {
        List<Drive> result = new ArrayList<>();
        ActiveXComponent axWMI = new ActiveXComponent("winmgmts://");

        try
        {
            Variant devices = axWMI.invoke("ExecQuery", new Variant("Select DeviceID,DriveType,FileSystem from Win32_LogicalDisk"));
            EnumVariant deviceList = new EnumVariant(devices.toDispatch());
            while (deviceList.hasMoreElements())
            {
                Dispatch item = deviceList.nextElement().toDispatch();
                String drive = Dispatch.call(item, "DeviceID").toString().toUpperCase();
                File file = new File(drive + "/");
                DriveTypeEnum driveType = fromNative(DriveTypeEnum.class, Dispatch.call(item, "DriveType").getInt());
                String fileSystem = Dispatch.call(item, "FileSystem").toString();
                result.add(new Drive(fileSystem, driveType, file));
            }

            return result;
        } finally
        {
            closeQuietly(axWMI);
        }
    }

    private static void closeQuietly(JacobObject jacobObject)
    {
        try
        {
            jacobObject.safeRelease();
        } catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }

    public static void main(String[] arguments)
    {
        List<Drive> drives = getDrives();

        for (Drive drive : drives)
        {
            System.out.println(drive.toString());
        }
    }
}

Example output:

示例输出:

Drive{C:\: LocalDisk, fileSystem=NTFS}
Drive{D:\: LocalDisk, fileSystem=NTFS}
Drive{E:\: RemovableDisk, fileSystem=NTFS}
Drive{F:\: RemovableDisk, fileSystem=FAT32}
Drive{G:\: RemovableDisk, fileSystem=null}
Drive{Y:\: NetworkDrive, fileSystem=NTFS}

To use JACOB, add the JARand DLL's from the download as libraries in your project. This solution is Windowsonly of course.

要使用JACOB,请将下载中的JAR和添加DLL为项目中的库。这个解决方案Windows只是当然。

回答by Kundan

File[] roots = File.listRoots();
for(int i=0;i<roots.length;i++)
    System.out.println("Root["+i+"]:" + roots[i]);

回答by luciano

This code snippet works on Windows. It correctly reports USB pen drives as removable, but on my laptop a USB hard drive is marked as non removable. Anyway this is the best I found without using native code.

此代码段适用于 Windows。它正确地将 USB 笔式驱动器报告为可移动,但在我的笔记本电脑上,USB 硬盘被标记为不可移动。无论如何,这是我在不使用本机代码的情况下发现的最好的。

for (Path root : FileSystems.getDefault().getRootDirectories()) {
  FileStore fileStore = Files.getFileStore(root);
  System.out.format("%s\t%s\n", root, fileStore.getAttribute("volume:isRemovable"));
}

Source: this file that apparently comes from the JDK

来源:这个文件显然来自 JDK

回答by Chris Peto

The correct way is how Luciano answered with isRemovable property, but I recently had on win 10 that if I started from USB, then USBs were no longer found in that method.

正确的方法是 Luciano 如何回答 isRemovable 属性,但我最近在 win 10 上发现,如果我从 USB 启动,则在该方法中不再找到 USB。

So, I used, for Windows only, the following wmic calls:

因此,我仅针对 Windows 使用了以下 wmic 调用:

ArrayList<File> rootDirs = new ArrayList<File>();
if( isWin )
{


  if( i_dolog )
    LOG.info( "Windows found as OS." );
  ArrayList<String> partids = new ArrayList<String>();

  String results0 = execute( "wmic diskdrive where interfacetype='USB' assoc /assocclass:Win32_DiskDriveToDiskPartition" );
  String lines[] = results0.split( "\r\r\n" );
  for( String line : lines )
  {
    String test = "Win32_DiskPartition.DeviceID=";
    int index = line.indexOf( test );
    if( index >= 0 )
    {
      String partid = line.substring( index + test.length() + 1 );
      partid = partid.substring( 0, partid.indexOf( '"' ) );
      partids.add( partid );
    }
  }
  for( String partition : partids )
  {
    String results2 = execute( "wmic partition where (DeviceID='" + partition + "') assoc /assocclass:Win32_LogicalDiskToPartition" );
    String lines2[] = results2.split( "\r\r\n" );
    for( String line : lines2 )
    {
      String test = "Win32_LogicalDisk.DeviceID=";
      int index = line.indexOf( test );
      if( index >= 0 )
      {
        String partid = line.substring( index + test.length() + 1 );
        partid = partid.substring( 0, partid.indexOf( '"' ) );
        rootDirs.add( new File( partid + "\" ) );
      }
    }
  }
}