How to list restricted folders on Mac OS with Java?

61 Views Asked by At

I'm trying to run this snippet:

import org.apache.commons.io.IOUtils;

import java.io.IOException;

public class Main {

    public static void main(String[] args) throws IOException, InterruptedException {
        var home = System.getProperty("user.home");
        var location = home + "/Library/Application Support/MobileSync/Backup";
        var pb = new ProcessBuilder("ls", "-al", location);
        var p = pb.start();
        System.out.println(p.waitFor());
        IOUtils.copy(p.getInputStream(), System.out);
        IOUtils.copy(p.getErrorStream(), System.err);
    }

}

It should list a folder where iPhone's backups are stored. I'm getting the following output:

1 # exit code
total 0
ls: /Users/zjor/Library/Application Support/MobileSync/Backup: Operation not permitted

However, if I run the following command in the terminal under the same user it works well:

ls -al "/Users/zjor/Library/Application Support/MobileSync/Backup"
total 0
drwxr-xr-x    3 zjor  staff    96 Oct 23 15:01 .
drwxr-xr-x    3 zjor  staff    96 Jan 17  2023 ..
drwxr-xr-x@ 262 zjor  staff  8384 Oct 23 14:55 00003101-123456780CC3XXXX

As far as I understand, the app should request special permissions to access some folders. But how to do it?

Any advice is appreciated.

2

There are 2 best solutions below

6
Freeman On

to access restricted folders on Mac OS, you can also use the Files class from the java.nio.file package and you can use Files.list() method to list the contents of the specified directory,so if the directory is restricted, it will throw an IOException!

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {

    public static void main(String[] args) throws IOException {
        var home = System.getProperty("user.home");
        var location = home + "/Library/Application Support/MobileSync/Backup";
        var path = Paths.get(location);

        try {
            Files.list(path)
                    .forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
0
zjor On

So far, I ended up opening System Settings > Privacy & Security > Full Disk Access dialog and adding my IDE or a bundled app there. The snippet below shows how to open the dialog:

...
Desktop.getDesktop().browse(URI.create("x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles"));
...