In this shot, we will discuss how to write a Java
program to print the current working directory in which a program is executed.
We use the Path
class from the java.nio.file
package and then perform the following steps.
Pass an empty string to the Paths.get()
method to get the current relative path.
Use the toAbsolutePath()
method to convert the relative path to absolute path.
Call the toString()
method on the absolute path to convert the absolute path to string.
import java.nio.file.Path;import java.nio.file.Paths;public class Main {public static void main(String[] args) {Path currRelativePath = Paths.get("");String currAbsolutePathString = currRelativePath.toAbsolutePath().toString();System.out.println("Current absolute path is - " + currAbsolutePathString);}}