What is the best way to find the user's home directory in Java?
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)
.
How to get %HOMEPATH% of file system from java
String usersHomeDir = System.getProperty("user.home");
what is System.getProperty(user.home) output in windows?
It will be the home directory of the current logged in user. c:\Users\${current_user_name}
How do I get the Users Music Directory?
The correct way to get the path to special folders on Windows is to call a shell function like SHGetFolderPath
with the CSIDL_*
constants (CSIDL_MYMUSIC
in your case).
You need to use JNI or JNA in Java to do this. Examples can be found here and here.
And for completeness, reading from the registry is not the correct way to do this...
Is there something like user.home to get the \Users\Public directory in java?
The way to find the public directory is
System.getenv("PUBLIC");
This should get something like C:\Users\Public
, or if your main drive is D:
, D:\Users\Public
.
This Wikipedia article is a good reference for Windows environment variables.
java.io.File cannot recognize ~ symbol of home dir?
Why is this?
Because the ~
symbol is only understood by the Unix shell (and, confusingly, it was used in HTTP servers). Even if you wrote the program in C, it wouldn't understand ~
to designate the home directory of the current user.
To get the user's home directory, use System.getProperty("user.home")
. (Answer from What is the best way to find the users home directory in Java?)
Related Topics
Causes of Getting a Java.Lang.Verifyerror
What Causes Javac to Issue the "Uses Unchecked or Unsafe Operations" Warning
How to Make a Deep Copy of an Object
Getting a File'S Md5 Checksum in Java
Equals VS Arrays.Equals in Java
Why Is the Java Date API (Java.Util.Date, .Calendar) Such a Mess
Syntax For Creating a Two-Dimensional Array in Java
How to Access Java-Classes in the Default-Package
Why Are Arrays Covariant But Generics Are Invariant
Making a Robust, Resizable Swing Chess Gui
Including Dependencies in a Jar With Maven
Why Filter() After Flatmap() Is "Not Completely" Lazy in Java Streams
Understanding Java'S Protected Modifier
Try/Catch With Inputmismatchexception Creates Infinite Loop