Thursday, February 2, 2017

Using an external package with the Java Development Kit

External packages can be accessed once the compiler can find them.  They usually come in a .jar file. There is lots of advice online about how to tell javac to find them.  The three usual ways are to (1) reset the CLASSPATH environmental variable, (2) use the command-line parameter  -cp, or (3) put the .jar file in some ~\jre\lib\ext directory.

The method least likely to have later unwanted side-effects is (2).  To keep it simple, I put a customised version of javac and java in the working directory where I have the source of
my java program.

Here's an example:   The package JGraphT has classes and methods that do all the standard tasks that you might want on a graph. I wanted to use the Bron-Krombosch algorithm to find a maximum independent set of nodes. I found the package at www.jgrapht.org, downloaded it and put it in my directory $HOME/programs/java.  The .jar file I needed was then:

$HOME/programs/java/jgrapht-1.0.1/lib/jgrapht-core-1.0.1.jar

I made executable shell scripts myjavac and myjava, with the following content:

myjavac:

#!/bin/sh
# file myjavac
# Uses java with classpath to include jgrapht package(s)
javac -cp $HOME/programs/java/jgrapht-1.0.1/lib/jgrapht-core-1.0.1.jar \
$1

myjava:

#!/bin/sh
# file myjava
# runs a java class with a main, adding jgrapht package(s)
# and the current directory
# to the classpath
java -cp $HOME/programs/java/jgrapht-1.0.1/lib/jgrapht-core-1.0.1.jar:. \
$1

Notice the :. that adds the current directory to CLASSPATH, as well as the directory that has the JGraphT package.  I put the following lines into my java source:

import org.jgrapht.*;
import org.jgrapht.graph.*;
import org.jgrapht.alg.*;

Then I just went ahead as usual, using 

myjavac <ClassName>.java 

to compile and 

myjava <ClassName>

to execute, where <ClassName> stands for the name of my source file, instead of javac and java. If you needed to use any other command-line parameters with javac, you would have to make the obvious modifications.  


No comments:

Post a Comment