Get the Current Working Directory in Java

In this source code example, we show you how to get the current working directory in Java.

1. Get the Current Working Directory in Java

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

Output:

The current working directory is c:\corejava\file_tutorials
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.

2. Using Java7+ NIO

import java.nio.file.*;
public class HelloWorld{

     public static void main(String []args){
        Path currentRelativePath = Paths.get("");
        String s = currentRelativePath.toAbsolutePath().toString();
        System.out.println("Current absolute path is: " + s);
     }
}

Output:

Current absolute path is: c:\corejava\file_tutorials


Comments