Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the path of running java program [duplicate]

Tags:

java

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.

like image 546
Denim Datta Avatar asked Jul 09 '13 05:07

Denim Datta


People also ask

How do I find the current class path?

In short, to get the classpath using System class you should: Use the getProperty(String key) , for the java. class. path key.


Video Answer


1 Answers

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); 
like image 155
René Link Avatar answered Sep 22 '22 19:09

René Link