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.
The simplest way is to call the getClass() method that returns the class's name or interface represented by an object that is not an array. We can also use getSimpleName() or getCanonicalName() , which returns the simple name (as in source code) and canonical name of the underlying class, respectively.
The getName() method of java Class class is used to get the name of the entity, and that entity can be class, interface, array, enum, method, etc. of the class object. Element Type.
Class representing the name of a Java class. This class is immutable, and can therefore be safely used by multiple threads. Warning: The same reference is often returned by the getClassName factory method for multiple calls which use the same type name as its parameter.
getName() returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String.
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...
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With