In the terminal, we get present working directory using pwd
command. In this tutorial, we will see how to get present working directory in java program.
Present working directory in Java:
There are several ways to find the present working directory in java, see one by one.
1. System.getProperty(“user.dir”):
One of the easiest ways is reading from System
properties using user.dir value. It reads the present working directory from where the current file is being used.
public class PresentWorkingDirectory {
public static void main(String[] args) {
String pwd = System.getProperty("user.dir");
System.out.println(pwd);
}
}
Output:
/Users/chandra/Work/MyWork/java_samples
2. Java nio Paths:
Java nio
provides Paths class, it provides necessary utility methods.
import java.nio.file.Paths;
public class PresentWorkingDirectory {
public static void main(String[] args) {
getPresentWorkingDirectory();
}
private static void getPresentWorkingDirectory() {
String pwd = Paths.get("")
.toAbsolutePath()
.toString();
System.out.println(pwd);
}
}
Output:
/Users/chandra/Work/MyWork/java_samples
3. Java nio FileSystem:
Java nio
provides FileSystem class, it provides an interface to a file system and is the factory for objects to access files and other objects in the file system.
import java.nio.file.FileSystems;
public class PresentWorkingDirectory {
public static void main(String[] args) {
getPresentWorkingDirectory2();
}
private static void getPresentWorkingDirectory2() {
String pwd = FileSystems.getDefault()
.getPath("")
.toAbsolutePath()
.toString();
System.out.println(pwd);
}
}
Output:
/Users/chandra/Work/MyWork/java_samples
4. Java io File:
This is the legacy way of getting the current working directory.
import java.io.File;
public class PresentWorkingDirectory {
public static void main(String[] args) {
getPresentWorkingDirectory3();
}
private static void getPresentWorkingDirectory3() {
String pwd = new File("")
.getAbsolutePath();
System.out.println(pwd);
}
}
Output:
/Users/chandra/Work/MyWork/java_samples
References:
Happy Learning 🙂