Get the Current Working Directory in Java

Java 8Object Oriented ProgrammingProgramming

The method java.lang.System.getProperty() is used to obtain the system property. This system property is specified by the key which is the parameter for the method. To obtain the current working directory, the key used is user.dir.

A program that demonstrates this is given as follows −

Example

 Live Demo

public class Demo {
   public static void main(String[] argv) throws Exception {
      String currentDirectory = System.getProperty("user.dir");
      System.out.println("The current working directory is " + currentDirectory);
   }
}

The output of the above program is as follows −

Output

The current working directory is c:\JavaProgram

Now let us understand the above program.

The current working directory is obtained by using the key user.dir with the method java.lang.System.getProperty(). Then the current working directory is printed. A code snippet that demonstrates this is given as follows −

String currentDirectory = System.getProperty("user.dir");
System.out.println("The current working directory is " + currentDirectory);
raja
Published on 28-Feb-2019 06:51:59
Advertisements