In this article, we are going to present how to get the current working directory in Java.
Follow this link to check more Java IO related articles
2. Using system property
According to JDK 7 documentation current user directory is named by the system property
user.dir, and is typically the directory in which the JVM was invoked.
Let's create a simple POC (proof of concept) application to check how this property behaves when we run the program from different folders.
This sample Maven application will be using
maven-jar-plugin to build the executable
pom.xml file has the following structure:
WorkingDirectory is our base class that contains
main(...) method, that starts the program:
pom.xml we need to point this class in
Now let's build our application using
mvn install command:
We run this commend in
The output will be:
After we copy application JAR file to
The output will be:
3. Get a working directory in
Things are slightly different in the Windows operation system. Printing
user.dir system parameter in Windows could give you results as:
C:\WINDOWS\system32, because in most cases user-working-directory will be pointing to current-working-directory of a system process (cwd).
When you need to determine the current working directory in Java application running on Windows, you could check the following example snippets (probably one should work just fine for you):
In this article, we presented how to get the current working directory in Java applications. Unfortunately dedicated system property (
user.dir) that should hold a current working directory works a little bit different in
Linux operating systems. That because in
Windows Java applications are handled by the system and running as a process using
C:\WINDOWS\system32 libraries. Depending on how you start your Java program in Windows you will need to use a different approach. You can start by checking our example snippets available also on GitHub.