How to get current working directory in Java?

JavaPathWorking Directory

Java Problem Overview


Let's say I have my main class in C:\Users\Justian\Documents\. How can I get my program to show that it's in C:\Users\Justian\Documents?

Hard-Coding is not an option- it needs to be adaptable if it's moved to another location.

I want to dump a bunch of CSV files in a folder, have the program recognize all the files, then load the data and manipulate them. I really just want to know how to navigate to that folder.

Java Solutions


Solution 1 - Java

One way would be to use the system property System.getProperty("user.dir"); this will give you "The current working directory when the properties were initialized". This is probably what you want. to find out where the java command was issued, in your case in the directory with the files to process, even though the actual .jar file might reside somewhere else on the machine. Having the directory of the actual .jar file isn't that useful in most cases.

The following will print out the current directory from where the command was invoked regardless where the .class or .jar file the .class file is in.

public class Test
{
    public static void main(final String[] args)
    {
        final String dir = System.getProperty("user.dir");
        System.out.println("current dir = " + dir);
    }
}  

if you are in /User/me/ and your .jar file containing the above code is in /opt/some/nested/dir/ the command java -jar /opt/some/nested/dir/test.jar Test will output current dir = /User/me.

You should also as a bonus look at using a good object oriented command line argument parser. I highly recommend JSAP, the Java Simple Argument Parser. This would let you use System.getProperty("user.dir") and alternatively pass in something else to over-ride the behavior. A much more maintainable solution. This would make passing in the directory to process very easy to do, and be able to fall back on user.dir if nothing was passed in.

Solution 2 - Java

Use [CodeSource#getLocation()][1]. This works fine in JAR files as well. You can obtain CodeSource by [ProtectionDomain#getCodeSource()][2] and the ProtectionDomain in turn can be obtained by [Class#getProtectionDomain()][3].

public class Test {
    public static void main(String... args) throws Exception {
        URL location = Test.class.getProtectionDomain().getCodeSource().getLocation();
        System.out.println(location.getFile());
    }
}

Update as per the comment of the OP:

> I want to dump a bunch of CSV files in a folder, have the program recognize all the files, then load the data and manipulate them. I really just want to know how to navigate to that folder.

That would require hardcoding/knowing their relative path in your program. Rather consider adding its path to the classpath so that you can use ClassLoader#getResource()

File classpathRoot = new File(classLoader.getResource("").getPath());
File[] csvFiles = classpathRoot.listFiles(new FilenameFilter() {
    @Override public boolean accept(File dir, String name) {
        return name.endsWith(".csv");
    }
});

Or to pass its path as main() argument. [1]: http://docs.oracle.com/javase/6/docs/api/java/security/CodeSource.html#getLocation%28%29 [2]: http://docs.oracle.com/javase/6/docs/api/java/security/ProtectionDomain.html#getCodeSource%28%29 [3]: http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getProtectionDomain%28%29

Solution 3 - Java

File currentDirectory = new File(new File(".").getAbsolutePath());
System.out.println(currentDirectory.getCanonicalPath());
System.out.println(currentDirectory.getAbsolutePath());

Prints something like:

/path/to/current/directory
/path/to/current/directory/.

Note that File.getCanonicalPath() throws a checked IOException but it will remove things like ../../../

Solution 4 - Java

this.getClass().getClassLoader().getResource("").getPath()

Solution 5 - Java

If you want to get your current working directory then use the following line

System.out.println(new File("").getAbsolutePath());

Solution 6 - Java

If you want the absolute path of the current source code, my suggestion is:

String internalPath = this.getClass().getName().replace(".", File.separator);
String externalPath = System.getProperty("user.dir")+File.separator+"src";
String workDir = externalPath+File.separator+internalPath.substring(0, internalPath.lastIndexOf(File.separator));

Solution 7 - Java

I just used:

import java.nio.file.Path;
import java.nio.file.Paths;

...

Path workingDirectory=Paths.get(".").toAbsolutePath();

Solution 8 - Java

Who says your main class is in a file on a local harddisk? Classes are more often bundled inside JAR files, and sometimes loaded over the network or even generated on the fly.

So what is it that you actually want to do? There is probably a way to do it that does not make assumptions about where classes come from.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJustian MeyerView Question on Stackoverflow
Solution 1 - Javauser177800View Answer on Stackoverflow
Solution 2 - JavaBalusCView Answer on Stackoverflow
Solution 3 - Javacyber-monkView Answer on Stackoverflow
Solution 4 - JavaPeter De WinterView Answer on Stackoverflow
Solution 5 - JavarjrajsahaView Answer on Stackoverflow
Solution 6 - JavajmamatosView Answer on Stackoverflow
Solution 7 - Javauser3696181View Answer on Stackoverflow
Solution 8 - JavaMichael BorgwardtView Answer on Stackoverflow