windows 如何在 Java 中找到“我的文档”文件夹

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1503555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 13:12:52  来源:igfitidea点击:

How to find "My Documents" folder in Java

javawindows

提问by Attilah

I'm willing to save a file in the user's "My Documents" folder.

我愿意在用户的“我的文档”文件夹中保存一个文件。

I tried getting the location like this :

我尝试获取这样的位置:

System.getenv("USERPROFILE") + "\My Documents\"

Then, I realized this wouldn't work in a system where the language is set to another language, french for example.

然后,我意识到这在语言设置为另一种语言(例如法语)的系统中不起作用。

Is there another way of getting the "My Documents" folder efficiently?

有没有另一种方法可以有效地获取“我的文档”文件夹?

回答by Simon Groenewolt

If you don't mind depending on Swing you can apparently use this trick:

如果你不介意依赖 Swing,你显然可以使用这个技巧:

import javax.swing.JFileChooser;
javax.swing.filechooser.FileSystemView;

public class GetMyDocuments {
  public static void main(String args[]) {
     JFileChooser fr = new JFileChooser();
     FileSystemView fw = fr.getFileSystemView();
     System.out.println(fw.getDefaultDirectory());
  }
}

(source: http://www.rgagnon.com/javadetails/java-0572.html)

(来源:http: //www.rgagnon.com/javadetails/java-0572.html

回答by IvanRF

Regarding performance, this is fasterthan using JFileChooser:

关于性能,比使用更快JFileChooser

FileSystemView.getFileSystemView().getDefaultDirectory().getPath()

In my PC, JFileChooserapproach needed 300ms, and calling FileSystemViewdirectly needed less than 100ms.

在我的PC中,JFileChooser方法需要300ms,FileSystemView直接调用需要不到100ms。

回答by laalto

There's winfoldersjava JNI extensionfor accessing special folder names in Java.

有用于访问 Java 中特殊文件夹名称的winfoldersjava JNI 扩展

The winfoldersjava page also describes another method using Swing:

winfoldersjava 页面还描述了另一种使用 Swing 的方法:

Also, if you need only the "My documents" path and don't mind touching Swing you may not need WinFoldersJava. You can use javax.swing.filechooser.FileSystemView.getFileSystemView().getDefaultDirectory() instead.

此外,如果您只需要“我的文档”路径并且不介意接触 Swing,则您可能不需要 WinFoldersJava。您可以使用 javax.swing.filechooser.FileSystemView.getFileSystemView().getDefaultDirectory() 代替。

回答by JRL

The location for that directory can be changed by each user, so it's not just dependent on the locale.
To find where that folder is, you have to look into the registry. The Windows command to do so is either:

每个用户都可以更改该目录的位置,因此它不仅仅取决于语言环境。
要找到该文件夹​​的位置,您必须查看注册表。执行此操作的 Windows 命令是:

reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User
Shell Folders" /v personal

or

或者

reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell 
Folders" /v personal

not sure which location actually, but it's one of them.

不确定实际上是哪个位置,但它是其中之一。