I need to find my documents path using Java. The following code doesn\'t give me \"accurate\" loation
System.getProperty(\"user.home\");
What sh
Note in 2020: The ShellFolder class seems to be missing on Linux (tested with openjdk8), so IvanRF's answer is likely better.
The best way I've found is to use AWTs:
ShellFolder.get("fileChooserDefaultFolder");
I have redirected my Documents folder to the D: drive, and it successfully fetches this directory. It also does so in about 40 ms (on my machine). Using FileSystemView
takes about 48 ms, and new JFileChooser()
about 250 ms.
All three of these methods actually use ShellFolder
under the hood, and the difference with FileSystemView
is negligible, but calling it directly avoids the overhead of the other two.
Note: You can also cast this directly to File
instead of implicitly getting the toString()
method of it, which can help you further:
File documents = (File) ShellFolder.get("fileChooserDefaultFolder");
Using JNA you would do this:
String myDocsPath = Shell32Util.getFolderPath(ShlObj.CSIDL_PERSONAL);
JNA extracts a DLL on-the-fly and then uses JNI with this DLL to make Windows API calls. It hides all the JNI details from you though. Using JNA is as easy as using any other java library JAR.