What is the best way to find the user's home directory in Java?
The difficulty is that the solution should be cross-platform; it should work on Windows 2000, XP, Vista, OS X, Linux, and 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.
Per Java bug 4787931, system property user.home
does not work correctly on Windows XP, so using this system property is not an acceptable solution as it is not cross-platform.
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)
.