Java: How to get the current user directory in a Java application

Java directory FAQ: Can you share an example of how to determine the current directory in Java?

You can determine the current directory your Java application is started in using System.getProperty() method and the user.dir property, like this:

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

Here’s a complete example:

public class JavaCurrentDirectoryExample {
  public static void main(String[] args) {
    String currentDirectory = System.getProperty("user.dir");
    System.out.println("user.dir: " + currentDirectory);
  }
}

Discussion

When you compile and run this little program, the output will show you the directory you ran the program in.

Accessing this Java property is often helpful when you want to store or read configuration, input, or output files that are related to your application.

You can get a full listing of all available Java properties at this URL.

Java current directory and web servers

When I wrote this tip, I was working on a Java/Swing/GUI application, and it works as advertised in those types of applications. I’ve been told that you can get varied results with this “current directory” technique using different Java web/application servers, like Tomcat or Glassfish. I’m sorry, I’m not working on any web projects at the moment, so I don’t know the correct cross-platform approach to get something like the web server directory. Whenever I get back to working on a Java web project I’ll be glad to update this article, or if anyone knows the correct answer, please leave a note below.