In Java, we can get the current working directory in different ways.
user.dir
Sysyem propertyuser.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.
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
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);}}