在Java中获取我的文档路径 [英] Getting My Documents path in Java

查看:45
本文介绍了在Java中获取我的文档路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用Java找到我的文档路径。以下代码没有给我准确的信息

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

System.getProperty(user.home);

相反应该是什么?

PS:
我不想要使用JFileChooser脏技巧。

P.S: I don't want to use the JFileChooser Dirty trick.

推荐答案

您可以使用注册表查询获取它,不需要JNA或管理员权限。

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");

显然除了Windows之外的任何事情都会失败,我不确定这是否适用于Windows XP 。

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

编辑:
把它放在一个有效的代码序列中:

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);

注意这将锁定进程直到reg query完成,这可能会导致麻烦依赖于什么你在干嘛。

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

这篇关于在Java中获取我的文档路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆