120

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.

The Guy with The Hat
  • 10,836
  • 8
  • 57
  • 75
Justian Meyer
  • 3,623
  • 9
  • 35
  • 53

8 Answers8

160

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.

  • I'll test this out when I can. I'm really preoccupied with that .jar issue :P – Justian Meyer Jul 01 '10 at 13:37
  • did you visit the link in my answer to that .jar issue, where I show how to build the .jar file with ANT? –  Jul 01 '10 at 14:37
  • 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"); –  Oct 24 '13 at 13:45
80

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 3
    +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. – erickson Jun 30 '10 at 21:09
  • 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: http://stackoverflow.com/questions/3152240/jar-cant-find-main-method-connected-to-main-class-but-cant-access-method . 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. – Justian Meyer Jun 30 '10 at 21:13
  • 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 Jun 30 '10 at 21:28
  • 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". – BalusC Jun 30 '10 at 21:35
  • It can't seem to find ClassLoader. – Justian Meyer Jul 01 '10 at 14:55
  • 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 ;) – BalusC Jul 01 '10 at 15:03
  • -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 =/. – Justian Meyer Jul 01 '10 at 15:11
  • `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... – BalusC Jul 01 '10 at 15:23
  • Why would. `public static String getCleanPath() { URL location = ExcelFile.class.getProtectionDomain().getCodeSource() .getLocation(); String path = location.getFile(); return new File(path).getParent(); }` Not work? – Justian Meyer Jul 01 '10 at 15:49
  • "It does not work" is too ambiguous. Be more precise. Also, why do you keep preferring this above `new File(classLoader.getResource("").getPath())` – BalusC Jul 01 '10 at 16:33
  • Could you add the import associated with the url class please ? Two many url class on the web to find the right one. – Moebius Aug 29 '14 at 15:27
  • @Moebius: just the one as returned by `getLocation()` method. – BalusC Aug 29 '14 at 15:53
  • @BalusC so the url class is not a standard class, but created by the user ? – Moebius Sep 01 '14 at 10:15
  • 1
    @Moebius: Huh? Are you new to Java? [Check the javadoc](http://docs.oracle.com/javase/7/docs/api/java/security/CodeSource.html#getLocation()). Just use exactly that one as returned by `getLocation()` method. Other ones are obviously not going to work. – BalusC Sep 01 '14 at 10:16
  • BalusC, what is the name of the convention you are using with the "#" between the class name and the method name? Thank you. – Sabuncu Dec 27 '14 at 10:36
  • @Sabuncu: javadoc style. – BalusC Dec 27 '14 at 10:37
32
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 ../../../

cyber-monk
  • 5,470
  • 6
  • 33
  • 42
15
this.getClass().getClassLoader().getResource("").getPath()
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Peter De Winter
  • 1,183
  • 2
  • 15
  • 27
7

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

System.out.println(new File("").getAbsolutePath());
rjrajsaha
  • 79
  • 1
  • 5
6

I just used:

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

...

Path workingDirectory=Paths.get(".").toAbsolutePath();
user3696181
  • 79
  • 1
  • 3
5

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));
jmamatos
  • 59
  • 1
  • 1
  • This does not work when you run it on an IDE or using something to spin the instance. – Sarp Kaya Sep 07 '15 at 00:50
  • 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 ? – JAVA Nov 14 '17 at 04:52
3

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.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
  • 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. – Justian Meyer Jun 30 '10 at 21:06
  • 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? – Chris Thompson Jun 30 '10 at 21:17
  • 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]") – Justian Meyer Jun 30 '10 at 21:32
  • 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? – Chris Thompson Jun 30 '10 at 21:44