Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting directory path to .class file containing main

Tags:

java

file

path

Is it possible to get the path to my .class file containing my main function from within main?

like image 535
Hamza Yerlikaya Avatar asked Apr 22 '09 16:04

Hamza Yerlikaya


1 Answers

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 189
erickson Avatar answered Nov 02 '22 21:11

erickson