在Java中查找用户主目录的最佳方法是什么? [英] What is the best way to find the users home directory in Java?
问题描述
困难在于它应该是跨平台的。 Windows 2000,XP,Vista,OSX,Linux,其他unix变体。我正在寻找可以为所有平台实现此目的的代码片段,以及一种检测平台的方法。
The difficulty is that it should be cross platform. Windows 2000, XP, Vista, OSX, Linux, other unix variants. I am looking for a snippet of code that can accomplish this for all platforms, and a way to detect the platform.
现在,你应该知道错误4787931 user.home
不能正常工作,所以请不要向我提供课本答案,我可以在手册中找到这些答案。
Now, you should be aware of bug 4787931 that user.home
does not work correctly, so please do not provide me of textbook answers, I can find these myself in the manuals.
推荐答案
您引用的错误(错误4787391)已在Java 8中修复。即使您使用的是旧版本的Java, System.getProperty(user.home)
方法可能仍然是最好的。 user.home
方法似乎适用于大量案例。 Windows上的100%防弹解决方案很难,因为Windows对主目录的含义有不同的概念。
如果 user.home
对你不够好我建议为windows选择主目录
的定义并使用它,用系统获取相应的环境变量.getenv(String)
。
The bug you reference (bug 4787391) has been fixed in Java 8. Even if you are using an older version of Java, the System.getProperty("user.home")
approach is probably still the best. The user.home
approach seems to work in a very large number of cases. A 100% bulletproof solution on Windows is hard, because Windows has a shifting concept of what the home directory means.
If user.home
isn't good enough for you I would suggest choosing a definition of home directory
for windows and using it, getting the appropriate environment variable with System.getenv(String)
.
这篇关于在Java中查找用户主目录的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!