Creating a JAR file with only the classes needed
by tgutwin
Posted on Sunday Jan 29, 2017 at 01:46PM in Programming
Have you ever wanted to create a JAR file for your Java class but only wanted to collect and jar the class files required by your class?
I found a very useful class to do this for you: It is called:
ZipLock written by Stuart D. Gathman at his company Business Management Systems.
Direct link to Original ZipLock.java file.
Its perfectly simple and GNU OpenSource! Thanks Stuart.
I also wrote a simple bash script below to wrap the calling of the java class...
My bash script does a few extra things
- it wraps the always cumbersome call to the ZipLock java class with an appropriate classpath
- it also adds a manifest to the jar pointing directly at the class you wanted to jar up, so it is a self executing jar file.
Here it is:
#!/bin/bashJAVA_HOME="/opt/jdk"
className=$1if [ "$#" -eq 0 ]; then
echo "Create a jar file for the passed in classname with only the required classes."
echo "It uses ZipLock"
echo ""
echo "jarItUp classname [classpath] "
echo ""
echo " - classname is the base class used to find dependant classes for the jar"
echo " - classpath is an optional EXTRA claspath that gets added to the default classpath that gets searched"elif [ "$#" -eq 1 ]; then
className="$1"
IFS='.' read -ra ADDR <<< "$1"
pkgLen=$((${#ADDR[*]} - 1))
jarName="${ADDR[${pkgLen}]}.jar"
command="${JAVA_HOME}/bin/java -cp "\
".:"\
"/mnt/warp4/home/share/dev/work/open/trunk/projects/WebARTS/build/classes:"\
"/mnt/warp4/home/share/pkgs:/home/tgutwin/pkgs:"\
"/mnt/warp4/home/share/dev/lib/geotools/classes"\
" ca.bc.webarts.tools.ZipLock "\
" -a ${jarName} "\
"$1"elif [ "$#" -eq 2 ]; then
cp="$2"
echo "cp=${cp}"
className="$1"
echo "classname=$2"
IFS='.' read -ra ADDR <<< "$2"
pkgLen=$((${#ADDR[*]} - 1))
jarName="${ADDR[${pkgLen}]}.jar"
command="${JAVA_HOME}/bin/java -cp "\
".:${cp}:"\
"/mnt/warp4/home/share/dev/work/open/trunk/projects/WebARTS/build/classes:"\
"/mnt/warp4/home/share/pkgs:/home/tgutwin/pkgs:"\
"/mnt/warp4/home/share/dev/lib/geotools/classes"\
" ca.bc.webarts.tools.ZipLock "\
" -a ${jarName} "\
"$1"fi
if [ "$#" -ne 0 ]; then
# echo "Running ${command}"
$command#echo "Running ${command[@]}"
#"${command[@]}"echo "Adding Manifest to new JAR file..."
printf '%s: %s\n' 'Manifest-Version' '1.0' > /tmp/manifest.txt
printf '%s: %s\n' 'Main-Class' "$className" >> /tmp/manifest.txt
printf '%s: %s\n\n' 'Permissions' 'all-permissions' >> /tmp/manifest.txt
# printf '%s: %s\n\n' 'Codebase' '$className' >> /tmp/manifest.txttmpUnzipDir="/tmp/jarClasses"
unzipCmd="unzip -oqq ${jarName} -d ${tmpUnzipDir}"
# echo "Running ${unzipCmd}"
$unzipCmdreJarCmd="jar cfm /tmp/${jarName} /tmp/manifest.txt -C ${tmpUnzipDir} ."
# echo "Running ${reJarCmd}"
$reJarCmdif [ "$?" -eq 0 ]; then
rm -f ${jarName}
mv -f /tmp/${jarName} ${jarName}
echo "Job done (retVal="$?") New jar is at ${jarName}"
fifi
Tags: java opensource