1. Introduction
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 user.dir
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 jar
file.
The pom.xml
file has the following structure:
The WorkingDirectory
is our base class that contains main(...)
method, that starts the program:
In pom.xml
we need to point this class in configuration.archive.manifest.mainClass
path:
Now let's build our application using mvn install
command:
We run this commend in /home/frontbackend/tutorials/java/java-io-working-directory
folder:
The output will be:
After we copy application JAR file to /tmp
folder:
The output will be:
3. Get a working directory in Windows
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):
Using FileSystems.getDefault()
method:
Using getClass().getProtectionDomain().getCodeSource()
method:
Using getPath(".")
method:
4. Conclusion
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 Windows
and 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.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}