Getting the path to the .class file containing the main

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

+13
java file path
Apr 22 '09 at 16:47
source share
4 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 compiled into JAR files, so this will not work in every case (hence IllegalStateException ). However, you can find the JAR that contains the class using this technique, and you can get the contents of the class file by replacing the call to getResourceAsStream() instead of getResource() , and this will work whether the class is included in the file system or in the JAR.

+28
Apr 22 '09 at 17:02
source share

According to http://www.cs.caltech.edu/courses/cs11/material/java/donnie/java-main.html , no. However, I suggest reading $ 0 (program name) in Java? Open the main class? which at least gives you the main class.

0
Apr 22 '09 at 16:50
source share

Why do you need this? If you need this to get files in the same directory, then for Class.getResourceAsStream () . >

0
Apr 22 '09 at 17:03
source share

This is more like an end user problem. Also consider the possible need to run multiple instances of any particular application and prevent users from doing so will be a serious annoyance.

If the problem is related to temporary file conflicts, just make sure that all of your temporary files have unique names. This, as I understand it, is the most common reason why people feel the need to prevent multiple instances of their applications from running.

PS: The java.io.File.createTempFile () methods are ideal for preventing temporary file conflicts because they automatically generate unique file names.

0
Jul 30 '09 at 19:39
source share



All Articles