How to get current working directory in Java?

372,205

Solution 1

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

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

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.

Solution 3

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

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

Solution 5

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

System.out.println(new File("").getAbsolutePath());
Share:
372,205

Related videos on Youtube

Justian Meyer
Author by

Justian Meyer

Graduated from Georgia Institute of Technology in Dec 2014 with degree focus on Information/Internetworks and Intelligence. Started my programming journey at 10 years old with DarkBasic and have since gone on to work at two top tech companies in Silicon Valley.

Updated on July 08, 2022

Comments

  • Justian Meyer
    Justian Meyer almost 2 years

    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.

    • Matthew J Morrison
      Matthew J Morrison almost 14 years
      take a look at this article.
    • Mattias Nilsson
      Mattias Nilsson almost 14 years
      What if your main class is in a jar file? What sort of result would you want then?
    • Ed S.
      Ed S. almost 14 years
      Why would you ever need to do this anyway?
    • Admin
      Admin almost 14 years
      sounds like what you need is the directory the CSV files are in, and have the .jar file be able to reference that directory, see my answer if that is the case.
    • Kevin
      Kevin over 9 years
    • Justian Meyer
      Justian Meyer over 9 years
      @Kevin: This was posted roughly a year before the linked post. Unsure if any information has become deprecated, however.
    • Paul Draper
      Paul Draper over 9 years
      @MatthewJMorrison, broken.
  • Justian Meyer
    Justian Meyer almost 14 years
    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.
  • brady
    brady almost 14 years
    +1. There are several conditions to make this work; the most important is that your "main class" is loaded from the file system. In Java, it's not terribly unusual for this assumption to be false. But, if you are sure that you are loading your class from a JAR on the file system, this is the method that works.
  • Justian Meyer
    Justian Meyer almost 14 years
    It all depends, really. I'm trying to get my JAR to compile, but that's a separate issue at the moment. If you think you can help with that, check out: stackoverflow.com/questions/3152240/… . I'm sure that posting this is an infraction of some kind, but it is related to this issue. If I can get that fixed, this will for sure be my answer.
  • Chris Thompson
    Chris Thompson almost 14 years
    Maybe I'm missing something but it seems like an absolute path would work. You said you can't hardcode it, but how are you going to know what folder to look in to begin with?
  • Justian Meyer
    Justian Meyer almost 14 years
    Why would I need to hardcode that? I've done similar things before. Assume that my jar and folder will always have a similar relationship (i.e. in the same directory). If this was true, I could get the directory of the jar, then modify it to find the folder.
  • Justian Meyer
    Justian Meyer almost 14 years
    Well the issue is that I want to bring it over to other computers, not just my own. I don't see how hardcoding the path would work. "Assume that my jar and folder will always have a similar relationship (i.e. in the same directory). If this was true, I could get the directory of the jar, then modify it to find the folder." The only way I could hardcode it would be if I didn't have to include the full path from the hard drive to the file. Maybe I can go just 3 folders back (i.e "Documents\Project\Dump\[file/folder]")
  • BalusC
    BalusC almost 14 years
    If it's in the same folder as the JAR file, then it's just already in the classpath. The word "hardcoding" is a bit exaggerated, I actually meant "knowing their path relative to the JAR file".
  • Chris Thompson
    Chris Thompson almost 14 years
    I would say what you want to do is get a handle to the directory the jar file resides in. Would that accomplish your requirements?
  • Justian Meyer
    Justian Meyer almost 14 years
    I'll test this out when I can. I'm really preoccupied with that .jar issue :P
  • Admin
    Admin almost 14 years
    did you visit the link in my answer to that .jar issue, where I show how to build the .jar file with ANT?
  • Justian Meyer
    Justian Meyer almost 14 years
    It can't seem to find ClassLoader.
  • BalusC
    BalusC almost 14 years
    Depending on the context, just get it by getClass().getClassLoader() or Foo.class.getClassLoader() or (preferably) Thread.currentThread().getContextClassLoader(). There are also shorthand getResource() methods in Class. Read the javadocs ;)
  • Justian Meyer
    Justian Meyer almost 14 years
    -Chose as best answer- Quick question before you go. Best way to remove CC.jar from the path name? Recursion cutting off the segments before each "/", getting the name, then cutting the string down where it finds "CC.jar" or whatever I get from the recursion? Maybe a little overly confusing =/.
  • BalusC
    BalusC almost 14 years
    File#getParent(). So, you're going for the non-classpath approach? A bit clumsy since the JAR's root path is already covered by the classpath...
  • Justian Meyer
    Justian Meyer almost 14 years
    Why would. public static String getCleanPath() { URL location = ExcelFile.class.getProtectionDomain().getCodeSource() .getLocation(); String path = location.getFile(); return new File(path).getParent(); } Not work?
  • BalusC
    BalusC almost 14 years
    "It does not work" is too ambiguous. Be more precise. Also, why do you keep preferring this above new File(classLoader.getResource("").getPath())
  • Admin
    Admin over 10 years
    The code from Jarrod that returns the current working directory absolute path from System Property user.dir is much easy to use. System.getProperty("user.dir");
  • android developer
    android developer over 10 years
    note that this will return the path to the "bin/classes/", and not just "bin".
  • Moebius
    Moebius almost 10 years
    Could you add the import associated with the url class please ? Two many url class on the web to find the right one.
  • BalusC
    BalusC almost 10 years
    @Moebius: just the one as returned by getLocation() method.
  • Moebius
    Moebius almost 10 years
    @BalusC so the url class is not a standard class, but created by the user ?
  • BalusC
    BalusC almost 10 years
    @Moebius: Huh? Are you new to Java? Check the javadoc. Just use exactly that one as returned by getLocation() method. Other ones are obviously not going to work.
  • Sabuncu
    Sabuncu over 9 years
    BalusC, what is the name of the convention you are using with the "#" between the class name and the method name? Thank you.
  • BalusC
    BalusC over 9 years
    @Sabuncu: javadoc style.
  • Sabuncu
    Sabuncu over 9 years
    Thank you. (That was fast!)
  • To Kra
    To Kra almost 9 years
    Yours its not working, this is one is correct Paths.get("").toAbsolutePath();
  • Sarp Kaya
    Sarp Kaya almost 9 years
    This does not work when you run it on an IDE or using something to spin the instance.
  • abergmeier
    abergmeier over 7 years
    @ToKra If I do Paths.get("my/file").toAbsolutePath() I get /my/file, which is definitely not the cwd.
  • To Kra
    To Kra over 7 years
    @abergmeier I wrote "" in string not "my/file"
  • JAVA
    JAVA over 6 years
    Internal path is java\lang\Class External path is E:\BranchProduction1.4.0\FilesTestProject\src Working directory is E:\BranchProduction1.4.0\FilesTestProject\src\java\lang could you explain the output ?
  • velocity
    velocity over 4 years
    while debugging a running application using Intellij Idea, this returned "/C:/Program%20Files/Java/jdk1.8.0_112/:"