[java] How to run Java program in terminal with external library JAR

This should be simple but I have never done it before and didn't find any solution.

I am currently using Eclipse to code my program, which imports some external JAR library such as google data api library. I can use Eclipse to compile/build/run the program.

But now I want to run it in terminal, so where should I put those JAR files, and how to build and run the program?


This question is related to java jar

The answer is

You can do :

1) javac -cp /path/to/jar/file Myprogram.java

2) java -cp .:/path/to/jar/file Myprogram

So, lets suppose your current working directory in terminal is src/Report/

javac -cp src/external/myfile.jar Reporter.java

java -cp .:src/external/myfile.jar Reporter

Take a look here to setup Classpath

For compiling the java file having dependency on a jar

javac -cp path_of_the_jar/jarName.jar className.java

For executing the class file

java -cp .;path_of_the_jar/jarName.jar className

  1. you can set your classpath in the in the environment variabl CLASSPATH. in linux, you can add like CLASSPATH=.:/full/path/to/the/Jars, for example ..........src/external and just run in side ......src/Report/

Javac Reporter.java

java Reporter

Similarily, you can set it in windows environment variables. for example, in Win7

Right click Start-->Computer then Properties-->Advanced System Setting --> Advanced -->Environment Variables in the user variables, click classPath, and Edit and add the full path of jars at the end. voila