PreviousNext…

Random code snippet: getting user’s documents / home directory

Occasionally I like to throw out random tips without any context or, indeed, much point beyond their inherent usefulness for anyone Googling or Binging. So, whatever, here is the latest:

It is commonly-believed that grabbing the user.dir or user.home system properties in Java is good enough, when it comes to making use of a user’s documents folder. Well, they get you part of the way there (although they don’t necessarily mean what you think they mean), but if you want a more resilient bit o’code, this may float your boat (note that this makes use of the Swing API):

return javax.swing.filechooser.FileSystemView
  .getFileSystemView().getDefaultDirectory().getAbsolutePath();

Less useful on OS X (just returns a reference to the user’s home directory so you may as well just carry on with user.home) but good for Windows, where it returns a reference to the user’s “My Documents” folder—I think it’s internationalisation-friendly to boot.

Comments on this post are now closed.

About

I’m a software architect / developer / general IT wrangler specialising in web, mobile web and middleware using things like node.js, Java, C#, PHP, HTML5 and more.

Best described as a simpleton, but kindly. You can read more here.

";