107

Is there a way to get the path of main class of the running java program.

structure is

D:/
|---Project
       |------bin
       |------src

I want to get the path as D:\Project\bin\.

I tried System.getProperty("java.class.path"); but the problem is, if I run like

java -classpath D:\Project\bin;D:\Project\src\  Main

Output 
Getting : D:\Project\bin;D:\Project\src\
Want    : D:\Project\bin

Is there any way to do this?



===== EDIT =====

Got the solution here

Solution 1 (By Jon Skeet)

package foo;

public class Test
{
    public static void main(String[] args)
    {
        ClassLoader loader = Test.class.getClassLoader();
        System.out.println(loader.getResource("foo/Test.class"));
    }
}

This printed out:

file:/C:/Users/Jon/Test/foo/Test.class


Solution 2 (By Erickson)

URL main = Main.class.getResource("Main.class");
if (!"file".equalsIgnoreCase(main.getProtocol()))
  throw new IllegalStateException("Main class is not stored in a file.");
File path = new File(main.getPath());

Note that most class files are assembled into JAR files so this won't work in every case (hence the IllegalStateException). However, you can locate the JAR that contains the class with this technique, and you can get the content of the class file by substituting a call to getResourceAsStream() in place of getResource(), and that will work whether the class is on the file system or in a JAR.

8
  • Well you could always tokenize the result (cut around the ";" which seperate the entries). The classpath property usually contains several entries (e.g. libraries you are using and so on). Maybe you should rethink your requirements. If you are just interested in one folder, are you sure parsing the classpath is a good idea?
    – Matthias
    Commented Jul 9, 2013 at 5:57
  • 2
    @Matthias Please note that the path separator is different on different platforms. It is better to use System.getProperty("path.separator");
    – Uwe Plonus
    Commented Jul 9, 2013 at 5:58
  • 1
    stackoverflow.com/a/778246/1862502 Commented Jul 9, 2013 at 5:59
  • As always with this type of question. Why? What actual application feature are you trying to implement? Serialization of settings, a 'self uninstaller'..? Commented Jul 9, 2013 at 6:25
  • @AndrewThompson : actually the code is using some files from the Directory. But if I use "../.." then one/two ant build located in different directory is getting failed. By getting path at runtime, this problem is solved. Please tell if there is any easy way to prevent that. Commented Jul 10, 2013 at 12:23

4 Answers 4

148

Use

System.getProperty("java.class.path")

see http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

You can also split it into it's elements easily

String classpath = System.getProperty("java.class.path");
String[] classpathEntries = classpath.split(File.pathSeparator);
3
  • 15
    I don't see how this answer the question to be honest. The system property 'java.class.path' returns the whole classpath, JAR's and everything. The OP is asking for the path to the running main class (working directory).
    – monzonj
    Commented Feb 21, 2014 at 13:45
  • 1
    The working directory is not necessarily where the class files are ran from. The example the OP gave proves this. While this answer does include all the locations of the project components, he shows how you can separate them into their elements.
    – Larry
    Commented Mar 2, 2015 at 11:33
  • 8
    @monzonj I agree with you. The question evolved after I answered it. Thus my answer did not match anymore. But in the meanwhile a lot of people found that answer useful, because it fits to the headline. That's why I still keep it and do not delete it.
    – René Link
    Commented Dec 9, 2015 at 17:10
110

Try this code:

final File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());

replace 'MyClass' with your class containing the main method.

Alternatively you can also use

System.getProperty("java.class.path")

Above mentioned System property provides

Path used to find directories and JAR archives containing class files. Elements of the class path are separated by a platform-specific character specified in the path.separator property.

2
  • getCodeSource() returns null in my jvm (jetty) Commented May 9, 2017 at 8:53
  • would MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath() be not just sufficient? Why creating a File object? Commented Oct 27, 2021 at 3:27
27

You actually do not want to get the path to your main class. According to your example you want to get the current working directory, i.e. directory where your program started. In this case you can just say new File(".").getAbsolutePath()

1
  • 5
    From all answers this is the most accurate
    – monzonj
    Commented Feb 21, 2014 at 13:48
3
    ClassLoader cl = ClassLoader.getSystemClassLoader();

    URL[] urls = ((URLClassLoader)cl).getURLs();

    for(URL url: urls){
        System.out.println(url.getFile());
    }
4
  • 1
    this usually should give you just the path from where your application was started. This does not need to be where your main class is located at all.
    – Matthias
    Commented Jul 9, 2013 at 5:59
  • 4
    There is also no guarantee the system classloader is a URLClassLoader either :P Commented Apr 15, 2014 at 2:24
  • This was useful for me. Thanks
    – xbmono
    Commented Jul 4, 2018 at 23:08
  • 6
    ClassCastException: class jdk.internal.loader.ClassLoaders$AppClassLoader cannot be cast to class java.net.URLClassLoader
    – cdalxndr
    Commented Feb 3, 2021 at 17:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.