gpt4 book ai didi

java - 获取 Mac 中运行的驱动程序

转载 作者:行者123 更新时间:2023-12-01 15:12:30 25 4
gpt4 key购买 nike

我想找出 Mac 中运行 Java 应用程序的驱动器的根目录。我使用以下代码在 Windows 上运行它,但我不知道如何使其在 OSx 上也运行:

// Method to determine and return the drive the application is running on
public static String getDriveRunningOn(){
// Get the root of all the drives attached to the computer
File[] roots = File.listRoots();

// Get the actual location of the application

// Loop through the roots and check if any match the start of the application's running path
for(int i = 0; i < roots.length; i++)
if(getAppPath().startsWith(roots[i].toString())){
String root = roots[i].toString();
//if(root.endsWith(File.separator) && root.length() > 1) root = root.substring(0, root.length() - 1);
return root;
}

// If the above loop doesn't find a match, just treat the folder the application is running in as the drive
return ".";
}

public static String getAppPath(){
try{
String appPath = MyCellRenderer.class.getProtectionDomain().getCodeSource().getLocation().getPath();
appPath = URLDecoder.decode(appPath, "UTF-8");
return new File(appPath).getAbsolutePath();
}catch(Exception e){return "n/a";}
}

因此,如果应用程序位于 C:\App.exe 中,getDriveRunningOn() 将输出 C:\ 等等。我需要在 Mac OSX 上发生同样的事情。提前致谢

最佳答案

好吧,结果在 Mac File.listRoots() 上仅列出 /。我不确定这是否是因为它只将内部驱动器视为“根”或什么,但这就是它的作用。幸运的是,在 Mac 中,连接的所有驱动器/卷(包括 USB 驱动器,基本上是计算机中列出的驱动器)都显示为 /Volumes 目录中的文件夹。

因此,我只是在 getDriveRunningOn() 方法中添加了一个 if 语句,如果在 Mac 上,则返回 new File("/Volumes")。 listFiles() 到文件数组,而不是 File.listRoots()。简单:)

关于java - 获取 Mac 中运行的驱动程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12144098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com