tags:

views:

1064

answers:

3

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?

+2  A: 

System.getProperty("user.home")+File.separator+"Documents";

And don't worry about with localization, look:

macb:Documents laullon$ pwd
/Users/laullon/Documents

My OS X is in Spanish.

That doesn't mean it will be on everyone's machine. The proper method is to use (in Objective-C) NSSearchPathForDirectoriesInDomains - see http://developer.apple.com/DOCUMENTATION/Cocoa/Conceptual/LowLevelFileMgmt/Tasks/LocatingDirectories.html for more.
Andrew Medico
It turns out that OS X localization works by changing the name displayed to the user, not the actual filename. Reference below.http://developer.apple.com/documentation/MacOSX/Conceptual/BPInternational/Articles/LocalizingPathnames.html#//apple_ref/doc/uid/20002141-BBCFJBFB
oldbeamer
Makes life easy but I'm not sure I like it very much :)
Tony Edgecombe
A: 

On mac (as far as I know all recent 10.x variants) the "My Documents" directory is located at (from root):
/Users/< username >/Documents
Thus it is in the "Documents" sub-directory within the home directory for the user.

Demi
+2  A: 

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

vasi
Thanks, this just helped me - I needed it to find the user's music folder. The extension isn't a download; it's within the JRE bundled in Mac OS X. Therefore, you have to write this code reflectively if you have code that must compile on other platforms. Finally, a reference to all the folder types can be found at http://walteriankaye.com/as/foldertypes.html
Dan Gravell