How to access My documents folder in Java

Tom, October 26 2006
In Java there's a system property called user.home. On Windows, it usually contains a path like this: C:\Documents and Settings\tom. However I want my game to save all configuration, saved games and screenshots into My documents. And there's no way to get that path in Java.

You may ask "why not just get the java user.home property and append Desktop or My documents to that?". Well, that may work in the English version of Windows, but in other languages, Windows names the folders differently. Also, Vista has a different folder structure compared to WinXP. Calling the aforementioned API function is necessary to get the correct folder location.

My documents or Desktop or other special Windows locations can be retrieved using the SHGetSpecialFolderPath() function. So I created a simple interface to access SHGetSpecialFolderPath in Java. It consists of a single Java class and a small DLL that calls the win32 API. The two are connected using JNI - Java Native Interface.

And here it is: WinFoldersJava.zip. It contains full source code (Java and C), a precompiled DLL and Visual Studio 2003 project files. UPDATE: now on Google Code: code.google.com/p/winfolde…
To create something like this, you first create a Java class, declare some or all of the methods with the "native" keyword and without bodies (just like abstract methods). Then you use the javah utility to generate a C/C++ header file. And finally you write the native functions according to the generated header and use your favorite compiler to create a DLL. Don't forget to System.load() the DLL before using it.

Comments

You can also use javax.swing.filechooser.FileSystemView.getFileSystemView().getDefaultDirectory();
This will get the (platform specific!) default folder. On a Windows machine this is the My Documents folder.
Nice trick, Jeroen, thanks! Didn't know about that one before. However I want to avoid using Swing at all costs.
No HTML

Your comment

No HTML allowed. Strings that start with http:// will turn into clickable links automatically.

Spam protection. How much is two by three?

Name: Email:
Games
Devastro
Titan Attacks
Chocolate Castle
Shop
Buy Devastro
Buy more games
Newsletter
Subscribe
Unsubscribe
Blog
Latest posts
Browse all posts
Subscribe to feed
Contact
Contact us
Feedback form
Game name generator