Reputation: 3682
I'm creating an application that could be either an .exe
or a .jar
and I need to know which it is. Does anyone know how I can get the file name/extension of a program running in Java please? I can get the path of the program running but I can't get the name.
Upvotes: 12
Views: 24771
Reputation: 1
This snippet below should do the trick:
try {
Class cls = Class.forName(getClass().getCanonicalName());
ClassLoader cLoader = cls.getClassLoader();
String nomeDaClasse=cls.getCanonicalName().replace(".", "/").concat(".class");
System.out.println("nomeDaClasse = "+ nomeDaClasse);
String urlClasseJava = cLoader.getSystemResource(nomeDaClasse).toString();
_nomeArquivoJava=urlClasseJava.substring("jar:file:".length(), urlClasseJava.indexOf("!/"));
System.out.println("_nomeArquivoJava = "+ _nomeArquivoJava);
}
catch(Exception e) {
e.printStackTrace();
}
The output will look like this:
$ java -jar CasaInformatizada-0.1.4.jar
dez 03, 2020 5:27:49 PM br.com.cvra.monitorArduino.Principal subirEscrivao
INFORMAÇÕES: /var/tmp/monitorArduino.xml
nomeDaClasse = br/com/cvra/monitorArduino/Principal.class
_nomeArquivoJava = /var/tmp/CasaInformatizada-0.1.4.jar
This is based upon the follow sources:
https://www.infoworld.com/article/2077485/java-tip-120--execute-self-extracting-jars.html https://www.tutorialspoint.com/java/lang/classloader_getsystemresource.htm
Upvotes: 0
Reputation: 346260
The actual program running the JAR file would be java.exe
.
I suggest you approach the problem from a completely different angle and have the exe wrapper set a system property that the program queries. Or you could have it and the JAR manifest specify different main classes.
Upvotes: 5
Reputation: 11996
Make 'name of program' a property that is passed to your program via '-D' command-line switch, like so
java -Dprogram.name=myApp.jar -jar myApp.jar
Read it in your code like so
if ("myApp.jar".equals(System.getProperty("program.name"))) {
// perform appropriate actions...
}
Upvotes: 5