Daniel Bristol
Daniel Bristol

Reputation: 87

How to add external library in classpath?

I have a folder that contains these java files: Main, TableManager, CustomFileWriter, CustomFileReader plus the external library commons-lang3-3.0.jar.I'm trying to compile the Main.java with this command

javac -cp commons-lang3-3.0.jar Main.java

but it says cannot find symbol

TableManager table = new TableManager()

I create an instance of TableManager in Main class. Without the external library and compiling with just javac Main.java works fine. How can I fix this. I need the external library for the StringUtils. I'm not using frameworks. Just text editor and running to terminal.

Upvotes: 2

Views: 7344

Answers (4)

hamnur
hamnur

Reputation: 21

The "-cp" Option overwrites your classpath. So in order to successfully compile and run your java-app, you have to add the path of your Main.class file and the external library as arguments. Here the "." is the relative path to your Main.class file and commons-lang3-3.0.jar the relative path to the external library. Under Windows it is sometimes necessarry to use quotes.

To compile:

javac -cp ".;commons-lang3-3.0.jar" Main.java

To run:

java -cp ".;commons-lang3-3.0.jar" Main

Upvotes: 0

rj93
rj93

Reputation: 573

To compile a class (on windows) with a jar in the same direcory use:

javac -cp .;myjar.jar MyClass.java

To then run the class you can use:

java -cp .;myjar.jar MyClass

NOTE: on linux you will need to replace ; with :

Upvotes: 0

Pedro Gordo
Pedro Gordo

Reputation: 1865

You need the path, not just the jar name, like

javac -cp c:\home\ann\public_html\classes\compute.jar engine\ComputeEngine.java

You can check it in the documentation.

Upvotes: 0

Abdelhak
Abdelhak

Reputation: 8387

To compile a Java file and include a Jar file, enter the following command line:

  javac -cp jar-file Main.java

For multiple JAR files, separate the jar-files with semicolons ;, with the following command line:

  javac -cp jar-file1;jar-file2;jar-file3 Main.java

Upvotes: 2

Related Questions