Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4536

Get the Current Working Directory in Java

$
0
0

1. Overview

It’s an easy task to get the current working directory in Java, but unfortunately, there’s no direct API available in the JDK to do this.

In this tutorial, we’ll learn how to get the current working directory in Java with java.lang.System, java.io.File, java.nio.file.FileSystems, and java.nio.file.Paths.

2. System

Let’s begin with the standard solution using System#getProperty, assuming our current working directory name is Baeldung throughout the code:

static final String CURRENT_DIR = "Baeldung";
@Test
void whenUsingSystemProperties_thenReturnCurrentDirectory() {
    String userDirectory = System.getProperty("user.dir");
    assertTrue(userDirectory.endsWith(CURRENT_DIR));
}

We used a Java built-in property key user.dir to fetch the current working directory from the System‘s property map. This solution works across all JDK versions.

3. File

Let’s see another solution using java.io.File:

@Test
void whenUsingJavaIoFile_thenReturnCurrentDirectory() {
    String userDirectory = new File("").getAbsolutePath();
    assertTrue(userDirectory.endsWith(CURRENT_DIR));
}

Here, the File#getAbsolutePath internally uses System#getProperty to get the directory name, similar to our first solution. It’s a nonstandard solution to get the current working directory, and it works across all JDK versions.

4. FileSystems

Another valid alternative would be to use the new java.nio.file.FileSystems API:

@Test
void whenUsingJavaNioFileSystems_thenReturnCurrentDirectory() {
    String userDirectory = FileSystems.getDefault()
        .getPath("")
        .toAbsolutePath()
        .toString();
    assertTrue(userDirectory.endsWith(CURRENT_DIR));
}

This solution uses the new Java NIO API, and it works only with JDK 7 or higher.

5. Paths

And finally, let’s see a simpler solution to get the current directory using java.nio.file.Paths API:

@Test
void whenUsingJavaNioPaths_thenReturnCurrentDirectory() {
    String userDirectory = Paths.get("")
        .toAbsolutePath()
        .toString();
    assertTrue(userDirectory.endsWith(CURRENT_DIR));
}

Here, Paths#get internally uses FileSystem#getPath to fetch the path. It uses the new Java NIO API, so this solution works only with JDK 7 or higher.

6. Conclusion

In this tutorial, we explored four different ways to get the current working directory in Java. The first two solutions work across all versions of the JDK whereas the last two work only with JDK 7 or higher.

We recommend using the System solution since it’s efficient and straight forward, we can simplify it by wrapping this API call in a static utility method and access it directly.

The source code for this tutorial is available on GitHub – it is a Maven-based project, so it should be easy to import and run as-is.


Viewing all articles
Browse latest Browse all 4536

Trending Articles