This post provides the instructions how to run a Java program from Terminal with external library JAR.
When using Eclipse to code Java program, which imports some external JAR library, we can use Eclipse to compile/build/run the program.
But if we would like to run our Java program that used External library Jars from Terminal, where should we put those JAR files, and how to build and run the program.
- For compiling the java file having dependency on a jar
$ javac -cp /path/to/jar/file Myprogram.java
- For executing the class file
$ java -cp .:/path/to/jar/file Myprogram
Note: cp in the above commands refers to classpath, which is a parameter in Java Virtual Machine or the Java compiler that specifies the location of user-defined classes and packages. The parameter may be set either on the command-line, or through an environment variable.
For example, if your current working directory in terminal is src/report/
$ javac -cp src/external/myImportedJarfile.jar myJavaProgram.java $ java -cp .:src/external/myImportedJarfile.jar myJavaProgram
If you have multiple jar files a.jar,b.jar and c.jar. To add them to classpath
$javac -cp .:a.jar:b.jar:c.jar HelloWorld.java $java -cp .:a.jar:b.jar:c.jar HelloWorld
Note: on Windows, use “;” instead of “:”
Using Java 6 or later, the classpath option supports wildcards. Note the following:
- Use straight quotes (
Wild cards were introduced from Java 6. Class path entries can contain the basename wildcard character *, which is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR.
java -cp "lib/*" -jar %MAINJAR%
If you need only specific jars, you will need to add them individually. The classpath string does not accept generic wildcards like Jar*, .jar, hiber etc.
The following entry does not work:
java -cp "Halo.jar;lib/*.jar" ni.package.MainClass
Correct entry is :
java -cp "Halo.jar;lib/*" ni.package.MainClass