How to get user home directory in java for all OS?

DeeKay September 23, 2017 at 10:05 pm · JAVA API

How to get user home directory in java is the common question arises while creating Java/Swing GUI applications. You can get home directory of user using System.getProperty("user.home") function.

Below java code shows you how to get User home directory. This code will work on Java 1.8 for all OS.

/****************************************************************************************
 * Created on 09-2017 Copyright(c) https://kodehelp.com All Rights Reserved.
 ****************************************************************************************/
package com.kodehelp.java8.util;

/**
 * Created by https://kodehelp.com
 * Date: 09-2017
 */
public class GetUserHomeDirectory {

    public static void main(String [] args){

        String userHomeDirectory = System.getProperty("user.home");
        System.out.println("User Home Directory is ==> "+userHomeDirectory);
    }
}
Output:
Home Directory is ==> C:\Users\kodehelp

There is a bug#JDK-6519127 which don’t let you use above approach on Windows in Java 1.6 and 1.7. If you are using Java 1.6 or Java 1.7 and would like to get home directory of user on windows OS then you can use below approach

/****************************************************************************************
 * Created on 09-2017 Copyright(c) https://kodehelp.com All Rights Reserved.
 ****************************************************************************************/
package com.kodehelp.java8.util;

/**
 * Created by https://kodehelp.com
 * Date: 09-2017
 */
public class GetUserHomeDirectory {

    public static void main(String [] args){

        String userHomeDirectory = System.getenv("USERPROFILE");
        System.out.println("User Home Directory is ==> "+userHomeDirectory);
    }
}
Output:
Home Directory is ==> C:\Users\kodehelp