我想找出我的 Java 应用程序在 Mac 上运行的驱动器的根目录。我使用以下代码在 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 上发生同样的事情。提前致谢