简体   繁体   中英

How to create Windows executable from JAR

I have a simple Java program (lets call it MyProgram.java) that does some I/O, re-names some images, deletes a directory, etc. I've been browsing around S/O looking for a simple way to run a Java program's main method from command prompt. I've compiled the source code into a jar, and tried using Jar2EXE Wizard, however I kept getting an unexpected compilation error that I wasn't getting while running my code from the IDE.

Does any one have either a Jar -> EXE converter solution they've had success with or can walk me through how to run my program from a batch file?

[..]or can walk me through how to run my program from a batch file?

The simplest way is to execute:

java -jar YOUR_JAR_FILE.jar

in your batch file. However this requires a manifest file to be present in your jar file which specifies the Main class to use and jar files it depends on. If you do not want to work with a manifest file you can specify these things manually. If you do not depend on external jar files you can execute:

java -cp YOUR_JAR_FILE.jar some.package.Main

This will execute the public static main(String[] args) method in class some.package.Main contained in YOUR_JAR_FILE.jar.

If there are other jar files you depend on (in your case that would be IOUtils/FileUtils), specify those jar files as well:

java -cp YOUR_JAR_FILE.jar:library1.jar:library2.jar some.package.Main

(in your case library1 and library2 are IOUtils and FileUtils respectively).

You can specify any number of jar files and you can also use the wildcard *.jar to include all files in the current (or another) directory. Note however that you cannot write * or x*.jar or the like. Only *.jar (or some/directory/*.jar ) is accepted.

In 90% of the times, the order of the jar files does not make any difference. However sometimes it does make a difference: If a resource is loaded from the classpath (could be a class or something as simple as a configuration file), the jar files are searched in the order you specified. If a resource exists in multiple jar files, only the first one found will be used.

您可以考虑使用install4j。

If you want use batch file you can write this:

java -jar sources.jar 

If your code have more than 2 static void main(String[] args) you need explicitly hit the method:

java -jar sources.jar classes.package.Main 

Directory structure:

-\project\
-\project\run.bat
-\project\sources.jar

Take a look at JSmooth . It wraps your JARs as executables and provides options for detecting, and handling lack of, the JVM. I've used it on a simple app and it was painless.

Bonus: it is available as a portable app with no installation needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM