Different ways to get the current working directory in Java

In Java, we can get the current working directory in different ways.

1. Using the user.dir Sysyem property

  • First, we can use the user.dir System property. user.dir points to the directory where Java was started and executes the current program.
class Main {
public static void main( String args[] ) {
String userDirectory = System.getProperty("user.dir");
System.out.println(userDirectory);
}
}

In the above code, we used System.getProperty("user.dir"); to get System property "user.dir", which will return the user’s working directory.

2. Using Paths

We can call the Paths.get method by passing an empty string:

import java.nio.file.Paths;
import java.nio.file.Path;
class Main {
public static void main( String args[] ) {
Path currentDirPath = Paths.get("");
String currentDir = currentDirPath.toAbsolutePath().toString();
System.out.println(currentDir);
}
}

In the above code, we get the current directory path by sending an empty string as an argument to the Paths.get method, and converting the returned path into an absolute pathfull path from the root directory string.

3. Using File

This is similar to the above method, but instead of creating a Path, we will create a File object by passing an empty string as a file path. We then convert that to an absolute path using the getAbsolutePath method of the File object.

import java.io.File;
class Main {
public static void main( String args[] ) {
File currentDir = new File("");
String absolutePath = currentDir.getAbsolutePath();
System.out.println(absolutePath);
}
}