Question

I would like to find out the root of the drive that my Java application is running on in Mac. I have it working on Windows with the following code but I don't know how to make it work on OSx too:

// 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";}
    }

So if the app was located in C:\App.exe, getDriveRunningOn() would output C:\ and so on. I need the same to happen on Mac OSX. Thanks in advance

Was it helpful?

Solution

Ok so, it turns out on Mac File.listRoots() only lists /. I'm not sure whether this is because it only sees internal drives as 'roots' or what but that's what it does. Fortunately, in Mac, all drives/volumes attacthed (including USB drives, basically those listed in Computer) appear as folders in the /Volumes directory.

Therefore, I simply added an if statement in my getDriveRunningOn() method that, if on Mac, returns new File("/Volumes").listFiles() to the file array rather than File.listRoots(). Simples :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top