Java – How to find the user’s ‘Documents’ folder with Java in OS X

javamacos

I'd like to create a directory in the user's 'Documents' folder, but so far I've only found out how to get the user's home directory:

javax.swing.JFileChooser fr = new javax.swing.JFileChooser();
javax.swing.filechooser.FileSystemView fw = fr.getFileSystemView();
this.userDirectory = fw.getDefaultDirectory();

In Windows the above code returns the 'My Documents' directory, which is great, that's where the new documents are supposed to go. On OS X it only returns the home directory.

Adding 'Documents' to the returned path would cause problems with localization.

How can I do this?

Best Solution

You want to use Apple's eio.FileManager extension:

    static public String documentsDirectory()
            throws java.io.FileNotFoundException {
        // From CarbonCore/Folders.h
        final String kDocumentsDirectory = "docs";
        return com.apple.eio.FileManager.findFolder(
            com.apple.eio.FileManager.kUserDomain,
            com.apple.eio.FileManager.OSTypeToInt(kDocumentsDirectory)
        );
    }

Documentation