在 Java 中查找用户主目录的最佳方法是什么? [英] What is the best way to find the users home directory in Java?

查看:35
本文介绍了在 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.

现在,您应该知道 bug 4787931user.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.

推荐答案

您引用的错误 (bug 4787391) 已在 Java 8 中修复.即使您使用的是旧版本的 Java,System.getProperty("user.home") 方法可能仍然是最好的.user.home 方法似乎适用于很多情况.Windows 上的 100% 防弹解决方案很难,因为 Windows 对主目录的含义有一个不断变化的概念.

如果 user.home 对你来说不够好,我建议为 Windows 选择一个 home 目录 的定义并使用它,用 System 获取适当的环境变量.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屋!

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