Sep 29 2011

Find the Current Working Directory in Java

There are times when you don’t have full control of the location where your Java application runs from. This could happen because the application is installed in a location other than the one recommended by the installer, or because it ran from the IDE, or some other reason. For whatever reason, if you need to find the current working directory where your Java application runs there are two different approaches. The first approach is to use the File class and the current directory symbol to find the current directory. Remember that the single period “.” represents the current directory and two periods “..” represents the parent directory.

   String currentPath = new File(".").getCanonicalPath();

Unfortunately, using the File class throws an IOException. There is another approach that does not throw an exception and returns the same absolute path to the current directory where the Java application is running from.

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