How to get the path to launch a java program

Is there a way to get the core class path of a running Java program.

structure

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 =====

There is a solution here

  • Solution 1 ( John Skeet )

    foo package

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

This is printed:

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


  • Solution 2 ( Erickson )

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

Note that most class files are compiled into JAR files, so this will not work in every case (hence the IllegalStateException ). However, you can find the JAR that the class contains using this method, and you can get the contents of the class file by substituting getResourceAsStream() instead of getResource() , and this will work if the class is on the file system or in the JAR.

+75
java
Jul 09 '13 at 5:54 on
source share
4 answers

Try this code:

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

replace MyClass your class containing the main method.

Alternatively you can also use

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

The above system property provides

The path used to search directories and JAR archives containing class files. Class path elements are separated by the platform-defined character specified in the path.separator property.

+71
Jul 09 '13 at 5:58
source share

Using

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

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

You can also easily break it into elements.

 String classpath = System.getProperty("java.class.path"); String[] classpathEntries = classpath.split(File.pathSeparator); 
+116
Jul 09 '13 at 6:03
source share

In fact, you do not want the path to your main class. According to your example, you want to get the current working directory, that is, the directory in which your program was run. In this case, you can simply say new File(".").getAbsolutePath()

+19
Jul 09 '13 at 6:00
source share
  ClassLoader cl = ClassLoader.getSystemClassLoader(); URL[] urls = ((URLClassLoader)cl).getURLs(); for(URL url: urls){ System.out.println(url.getFile()); } 
-one
Jul 09 '13 at 5:57 on
source share



All Articles