我正在尝试打印驱动器号及其系统类型。在这个程序中,它将硬盘驱动器打印为逻辑驱动器,将CD驱动器打印为CD驱动器,将存储卡打印为可移动驱动器。当我插入外置硬盘和pendrive(sandisk cruzer blade 16 GB)时,它同时显示为逻辑驱动器。我想检测并打印外部硬盘和pendrive作为可移动设备'因为它们是便携式的。请帮我怎么做。 这是代码。
import javax.swing.filechooser.FileSystemView;
import java.io.File;
public static void main(String x[])
{
File paths[];
paths = File.listRoots();
for(File path: pahts)
{
System.out.println("Drive Name: "+path);
System.out.println("Description: "+fsv.getSystemTypeDescription(path));
}
}
答案 0 :(得分:0)
您可以使用特定于操作系统的命令并通过java Runtime
执行它。例如,在Windows中,您可以使用命令wmic来获取所有驱动器详细信息,例如设备名称,标题,文件系统,类型等。例如,wmic logicaldisk get deviceid driveType
将列出所有可用的驱动器号及其类型。逻辑磁盘有7种驱动器类型
0 = Unknown
1 = No Root Directory
2 = Removable Disk
3 = Local Disk
4 = Network Drive
5 = Compact Disc
6 = RAM Disk
正如您所见,类型2是您正在寻找的类型。除了逻辑磁盘之外,还可以使用wmic来检索系统的所有方面,如cpu,bios等。可以找到wmic中所有命令的列表here。
同样地,您在linux中有udevadm命令来获取设备详细信息,并在Mac中获取system_profiler。因此,如果您希望以独立于工厂形式的方式访问详细信息,则可以根据当前操作系统更改命令。使用System.getProperty("os.name")
来确定当前的操作系统。
Windows OS的示例程序
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class DriveDetails {
public static void main(String[] args) {
String command = "wmic logicaldisk where drivetype=$$ get deviceid";
for (DriveType driveType : DriveType.values()) {
String query = command.replace("$$", String.valueOf(driveType.getType()));
System.out.println(driveType.getDescription());
System.out.println(executeCommand(query).trim());
}
}
private static String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p = null;
BufferedReader reader = null;
try {
p = Runtime.getRuntime().exec(command);
reader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = "";
boolean flag = true;
while ((line = reader.readLine()) != null) {
if(flag) {
flag = false;
continue; // Skipping header
}
output.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (p != null)
p.destroy();
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return output.toString();
}
enum DriveType {
UNKNOWN(0, "Unknown"),
NO_ROOT_DIRECTORY(1, "No Root Directory"),
REMOVABLE_DISK(2, "Removable Disk"),
LOCAL_DISK(3, "Local Disk"),
NETWORK_DRIVE(4, "Network Drive"),
COMPACT_DISC(5, "Compact Disc"),
RAM_DISK(6, "RAM Disk");
private DriveType(int type, String description) {
this.type = type;
this.description = description;
}
private int type;
private String description;
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
}