Example to get user home directory in Java


In java getting user’s profile home directory is quite simple using System.getProperty("user.home") and it works in most of the cases. There is another property user.dir which returns current directory of execution. So don’t get confuse as both property holds different paths.

Code example to get user home directory and current directory of executing program

public class UserHomeDirExample {
    public static void main(String[]args){
        System.out.println(getUserHomeDir());
        System.out.println(getCurrentDir());
    }
    public static String getUserHomeDir() {
        return Paths.get(System.getProperty("user.home")).toAbsolutePath()
                .toString();
    }
    public static String getCurrentDir() {
        return Paths.get(System.getProperty("user.dir")).toAbsolutePath()
                .toString();
    }
}