Convert a JAR file into a Linux executable

      No Comments on Convert a JAR file into a Linux executable

With Java programs it’s quite common to combine several classes into one JAR archive. Java libraries are typically distributed this way as well.
On Linux platforms, people are quite used to using command line programs, but sometimes it’s handy to distribute a java program as an executable file that can be run by a simple double-click instead of opening a terminal and typing java -jar FancyProgram.jar. Of course, one could always configure the desktop environment to associate JAR files with the corresponding executable from the Java Runtime Environment, but adding the JAR archive as a payload to a common shell script is much more universal.

Here’s a small stub of code that will launch the Java interpreter (i.e. the binary called java) with itself as the JAR file to run.

#!/bin/sh
MYSELF=`which "$0" 2>/dev/null`
[ $? -gt 0 -a -f "$0" ] && MYSELF="./$0"
java=java
if test -n "$JAVA_HOME"; then
    java="$JAVA_HOME/bin/java"
fi
exec "$java" $java_args -jar $MYSELF "$@"
exit 1

To add the original JAR archive as payload and make the resulting file executable, run

cat stub.sh FancyProgram.jar > FancyProgram && chmod +x FancyProgram

You can now execute the resulting file with ./FancyProgram.

Binary payloads in shell scripts also allow you do distribute entire software packages that could easily consist of hundreds of files as a single shell script, as described in a great article from linuxjournal.com. To wrap JAR archives in native Windows executables, have a look at http://launch4j.sourceforge.net.

Resources:
https://coderwall.com/p/ssuaxa/how-to-make-a-jar-file-linux-executable

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.