Get User Home Directory in Java using Apache Commons IO

Tags: FileUtils Apache Commons Apache Commons IO File Directory

In this Java tutorial we learn how to get the user home directory using FileUtils class of Apache Commons IO library.

How to add Apache Commons IO library to your Java project

To use the Apache Commons IO library in the Gradle build project, add the following dependency into the build.gradle file.

implementation 'commons-io:commons-io:2.8.0'

To use the Apache Commons IO library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.8.0</version>
</dependency>

To have more information about the Apache Commons IO library you can visit the library home page at commons.apache.org/proper/commons-io/

How to get User home Directory in Java using FileUtils class

To get the user home directory as a File object we can use the method FileUtils.getUserDirectory() as the following example code.

GetUserDirectory.java

import org.apache.commons.io.FileUtils;

import java.io.File;

public class GetUserDirectory {
    public static void main(String... args) {
        File userDirectory = FileUtils.getUserDirectory();

        System.out.println("User directory is " + userDirectory);
    }
}
The output is:
User directory is C:\Users\SimpleSolution

The Apache Commons IO library also provides the method FileUtils.getUserDirectoryPath() to return the user home directory path as a String value.

GetUserDirectoryPath.java

import org.apache.commons.io.FileUtils;

public class GetUserDirectoryPath {
    public static void main(String... args) {
        String userDirectoryPath = FileUtils.getUserDirectoryPath();

        System.out.println("User directory path is " + userDirectoryPath);
    }
}
The output is:
User directory path is C:\Users\SimpleSolution

Happy Coding 😊