How to determine the directory your Java application was started in (user.dir)

If you ever need to determine what directory your Java code is being run from (essentially the current working directory), you can get this information from the system properties, specifically the System.getProperty or System.getProperties methods.

The following line of Java code shows how to determine what directory your Java application was started in. This information is stored in the user.dir system property, which you access like this:

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

I needed to do this while running my project in Eclipse, because for some reason I wasn't able to open up a file using a relative path. When I ran that line of code and printed out the result, it showed this output:

USER.DIR = C:\Work\CVSProjects\MyFooProject

(where the name of my project has been changed)

Knowing your current working directory can be valuable in a number of circumstances, not the least of which was trying to debug my particular problem.

Finally, here's a link that will help you find much more information about all the system properties and environment variables you can access from your Java code.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.