我需要使用Java找到我的文档路径.以下代码并没有给我"准确"的说明
System.getProperty("user.home");
相反应该是什么?
PS:我不想使用JFileChooser Dirty技巧.
xch*_*onx 30
这很容易,JFileChooser找到它
new JFileChooser().getFileSystemView().getDefaultDirectory().toString();
Run Code Online (Sandbox Code Playgroud)
我希望这可以帮助别人
Iva*_*nRF 23
由于来自@xchiltonx的最受欢迎的答案,JFileChooser我想补充一点,关于性能,这比使用更快JFileChooser:
FileSystemView.getFileSystemView().getDefaultDirectory().getPath()
Run Code Online (Sandbox Code Playgroud)
在我的电脑中,JFileChooseraproach需要300毫秒,FileSystemView直接呼叫需要不到100毫秒.
注意:问题是如何在Java中找到"我的文档"文件夹的可能重复
pdi*_*lag 11
您可以使用注册表查询来获取它,不需要JNA或管理员权限.
Runtime.getRuntime().exec("reg query \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell
Folders\" /v personal");
Run Code Online (Sandbox Code Playgroud)
显然,除了Windows之外,这将失败,我不确定这是否适用于Windows XP.
编辑:把它放在一个工作的代码序列中:
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);
Run Code Online (Sandbox Code Playgroud)
请注意,这将锁定进程,直到"reg query"完成,这可能会导致依赖于您正在执行的操作时出现问题.