getUserDir()
is a SystemUtils
class that is used to return the user directory of the host system as an instance of the File
class.
The path to the user directory is stored as a system property under the name user.dir
.
SystemUtils
The definition of SystemUtils
can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml
file:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the
commons-lang
package, refer to the Maven Repository.
You can import the SystemUtils
class as follows:
import org.apache.commons.lang3.SystemUtils;
public static File getUserDir()
The method accepts no parameters.
This method returns the File
object pointing to the user directory.
import org.apache.commons.lang3.SystemUtils;import java.io.File;public class Main{public static void main(String[] args){File userDir = SystemUtils.getUserDir();System.out.printf("The absolute path of the user directory is '%s'.", userDir.getAbsolutePath());}}
In the above code, we use the getUserDir()
method to get the File
object pointing to the user directory.
Next, we print the absolute path of the user directory.
The output of the code is as follows:
The absolute path of the user directory is '/Users/educative/Documents/test'.
Running the above code in your system may give different outputs, depending on your machine.
Free Resources