How to make a java jar file to be a single file executable?

1

1

I have a jar file with a main class in it. The main class is already configured in the manifest file, meaning the jar can be executed in the following way:

java -jar Main.jar

I'd like to make it executable, meaning running it in the following way, without the need to provide any parameter. Windows:

Main.cmd

or Linux:

Main.sh

How can I package the jar into an executable?

AlikElzin-kilaka

Posted 2015-05-10T11:53:39.383

Reputation: 1 341

There's an answer for Linux. Any idea how to package a java jar in an executable for Windows? – AlikElzin-kilaka – 2015-05-10T11:54:52.427

Honestly, how hard is it to search the net for "jar to exe"? There are a number of solutions available. – Karan – 2015-05-11T20:30:48.953

@karan great, then it will be easy to answer the question. – AlikElzin-kilaka – 2015-05-12T03:46:16.767

Definitely. You can edit your existing answer and add it in, then self-accept. – Karan – 2015-05-12T04:26:10.117

@Karan And deny you the credit? Na ;-) – AlikElzin-kilaka – 2015-05-12T05:14:25.787

1It's ok, you're welcome to it. :) In all seriousness though, a single canonical answer would be better because you've asked about multiple OSes, and unless an answer covers both it wouldn't be complete. – Karan – 2015-05-12T05:21:48.000

Answers

3

For Linux, there's a way: Package the jar in a bash file. Steps:

1- Create a stub:

MYSELF=`which "$0" 2>/dev/null`
[ $? -gt 0 -a -f "$0" ] && MYSELF="./$0"
exec java -jar $MYSELF "$@"
exit $?

2- Concatenate the stub and the jar into a new executable:

cat stub.sh Main.jar > main.sh

3- Make the new file executable:

chmod +x main.sh

That's it! Source: https://coderwall.com/p/ssuaxa/how-to-make-a-jar-file-linux-executable

AlikElzin-kilaka

Posted 2015-05-10T11:53:39.383

Reputation: 1 341

You can use shell emulators to run the shell script on Windows as well. Example of such emulator: GitBash and Cygwin. – AlikElzin-kilaka – 2015-05-12T05:15:48.073