Getting My Documents path in Java

后端 未结 8 1318
孤城傲影
孤城傲影 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条回答
  •  生来不讨喜
    2020-12-06 05:16

    You can get it using a registry query, no need for JNA or admin rights for that.

    Runtime.getRuntime().exec("reg query \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell 
    Folders\" /v personal");
    

    Obviously this will fail on anything other than Windows, and I am not certain whether this works for Windows XP.

    EDIT: Put this in a working sequence of code:

    String myDocuments = null;
    
    try {
        Process p =  Runtime.getRuntime().exec("reg query \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\" /v personal");
        p.waitFor();
    
        InputStream in = p.getInputStream();
        byte[] b = new byte[in.available()];
        in.read(b);
        in.close();
    
        myDocuments = new String(b);
        myDocuments = myDocuments.split("\\s\\s+")[4];
    
    } catch(Throwable t) {
        t.printStackTrace();
    }
    
    System.out.println(myDocuments);
    

    Note this will lock the process until "reg query" is done, which might cause trouble dependeing on what you are doing.

提交回复
热议问题