Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

classpath - running a java program from the command line

My code compiled fine with the following command:

javac -cp "../lib/*" AvroReader.java

(lib is where i put my jar files)

At run time I get a ClassNotFoundException on the following line:

DatumReader<?> dtmrdr = new GenericDatumReader();

It says it can't find org.apache.avro.generic.GenericDatumReader even though I've imported it.

Why is this happening?

like image 558
Dao Lam Avatar asked Jul 13 '12 00:07

Dao Lam


People also ask

What is CLASSPATH in command-line?

Classpath in Java is the path to the directory or list of the directory which is used by ClassLoaders to find and load classes in the Java program. Classpath can be specified using CLASSPATH environment variable which is case insensitive, -cp or -classpath command-line option or Class-Path attribute in manifest.

How do I find my Java classpath?

To check our CLASSPATH on Windows we can open a command prompt and type echo %CLASSPATH%. To check it on a Mac you need to open a terminal and type echo $CLASSPATH.


2 Answers

Importing has nothing to do with loading classes or setting CLASSPATH.

Try this:

java -cp .;../lib/* Generator

Using the dot '.' as the first entry in the CLASSPATH assumes that the Generator.class file exists in the directory from which you're running java, and /lib is one level up from that directory. Adjust as needed if both of these are not correct.

like image 179
duffymo Avatar answered Sep 21 '22 20:09

duffymo


You should run the program including again the same cp:

java -cp "lib directory where i put all the jars" MainClassOfYourApplication

After you compiled it with:

javac -cp "lib directory where i put all the jars" AvroReader.java

More applied to your example:

First step(compile all the needed java files): javac -cp "path/to/jars/*" AvroReader.java //here you should include all the java files not yet compiled but which you need to run your app
Second step: java -cp "path/to/jars/*" package.subpackage1.subpackage2.Generator
like image 34
Razvan Avatar answered Sep 18 '22 20:09

Razvan