Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting filesystem path of class being executed [duplicate]

Tags:

java

filepath

People also ask

How do you find the path of a class?

We can use the getClass() method of Object class in Java that returns the currently running class, which further can be used with the getPath() method to get the path of the current working directory.

How do I get the path of a jar file?

In Java, we can use the following code snippets to get the path of a running JAR file. // static String jarPath = ClassName. class . getProtectionDomain() .

How .class file is executed?

A Java class file is a compiled java file. It is compiled by the Java compiler into bytecode to be executed by the Java Virtual Machine.


The following code snippet will do this for you:

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

replace MyClass with your main class

The resulting File object f represents the .jar file that was executed. You can use this object to get the parent to find the directory that the .jar is in.