CodeGym/Java Blog/Java Developer/Get the Current Working Directory in Java
Author
Artem Divertitto
Senior Android Developer at United Tech

Get the Current Working Directory in Java

Published in the Java Developer group
members
Getting the current working directory in Java means getting the path of the directory (folder) from where your program has launched. Normally, that means to get the path from the root folder to the folder where the program file has been placed. This is a common day to day problem and there are multiple ways to do it in Java. However, we will start with the most basic one utilising the System’s built-in method.

Using System.getProperty(); Method

public class DriverClass {

	public static void main(String[] args) {

		String userDirectoryPath = System.getProperty("user.dir");

		System.out.println("Current Directory = \"" + userDirectoryPath + "\"" );
	}
}

Output

Current Directory = "C:\Users\DELL\eclipse-workspace\JavaProjects"

Explanation

The above code snippet uses the “getProperty()” method provided by the “System” with the standard parameter “user.dir”. It fetches the path of the directory containing your Java project. Run it for yourself and you will see it is printed in the output.

Using the java.nio.file.FileSystems

import java.nio.file.FileSystems;
import java.nio.file.Path;

public class DriverClass1 {

   // Print Current Working Directory using File Systems
   static void printCurrentWorkingDirectoryUsingFileSystems() {

	Path currentDirectoryPath = FileSystems.getDefault().getPath("");
	String currentDirectoryName = currentDirectoryPath.toAbsolutePath().toString();
	System.out.println("Current Directory = \"" + currentDirectoryName + "\"");

    }

    public static void main(String[] args) {
	printCurrentWorkingDirectoryUsingFileSystems();
    }
}

Output

Current Directory = "C:\Users\DELL\eclipse-workspace\JavaProjects"

Explanation

Java 7 and above can use the java.nio.file.FileSystems to get the current directory. In the above program, “getDefault()” method gets the default FileSystems. Then “getPath()” method fetches its path. Later, it is converted to “Absolute Path” to get the complete path of the working directory from the root. Since it returns a path type object, so a conversion using “toString()” is performed for printing on screen.

Conclusion

By now you must be familiar with two different ways of getting the current working directory in Java. Coming across these methods will only make sense if you run both of the above programs on your machines. Validate the output for yourself and keep us posted with any questions you might have. Till then, keep learning and keep growing!
Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet