Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java command-line problems with .jar libraries

I have a single .java (driver.java) file I'm trying to compile and run from the command-line. It uses the external library called EXT.jar, whose structure is just a folder called EXT with a few dozen classes within it.

So I run:

javac -cp EXT.jar driver.java

This compiles the class just fine.

then when I run:

java -cp EXT.jar driver

I get a java.lang.NoClassDefFoundError.

Oddly enough, if I unpack the JAR (so now I have a folder in the root directory called EXT), the last command works just fine!! Driver will execute!

Is there any way I can make the driver.class look for the need class files from EXT.jar/EXT/*class instead of an actual EXT folder?

Thanks!

like image 273
Monster Avatar asked Jun 16 '10 18:06

Monster


People also ask

How to execute jar file from java Code?

To run an application in a nonexecutable JAR file, we have to use -cp option instead of -jar. We'll use the -cp option (short for classpath) to specify the JAR file that contains the class file we want to execute: java -cp jar-file-name main-class-name [args …]

Which command is correct to create jar file?

The javac command creates JarExample. class in the com/baeldung/jar directory. We can now package that into a jar file.


1 Answers

You're compiling the class to the local directory. So when you run it, you need to include the current directory in your classpath. E.g.:

java -cp .;EXT.jar driver

Or in linux:

java -cp .:EXT.jar driver

With the way you have it now, you're saying your classpath is only EXT.jar (along with whatever is in the CLASSPATH environment variable) and nothing else (which is why the current directory, where driver.class is located, is excluded)

like image 52
Matt Avatar answered Sep 28 '22 20:09

Matt