Getting My Documents path in Java

后端 未结 8 1291
孤城傲影
孤城傲影 2020-12-06 04:21

I need to find my documents path using Java. The following code doesn\'t give me \"accurate\" loation

System.getProperty(\"user.home\");

What sh

相关标签:
8条回答
  • Note in 2020: The ShellFolder class seems to be missing on Linux (tested with openjdk8), so IvanRF's answer is likely better.

    Original answer:

    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");
    
    0 讨论(0)
  • 2020-12-06 05:20

    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.

    0 讨论(0)
提交回复
热议问题