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:

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

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.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.