Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a Java program from the command line that depends on a jar file?

I have a simple Java file Q.java that depends on an external library file X.jar. Both Q.java and X.jar are in the same directory. I can compile Q.java from the command line by doing: "javac -cp X.jar Q.java". This generates a Q.class file. How do I run this now? I tried all these:

1) java Q 2) java -cp X.jar Q

I keep getting a Exception in thread "main" java.lang.NoClassDefFoundError: Q Caused by: java.lang.ClassNotFoundException: Q

So how do I run this from the command line now that I have the class file?

like image 871
pathikrit Avatar asked Aug 14 '11 01:08

pathikrit


People also ask

How do I run a java program from a jar file?

Running Jar file require you to have the jar file included in your class path. This can be done at run time using URLClassLoader . Simply construct a URLClassLoader with the jar as one of the URL. Then call its forClass(...) if you know the class name (full name of course).


1 Answers

java -cp X.jar:. Q

You have to specify in the classpath that you want to use the JAR dependency AND the current local directory to resolve classes.


Edit suggested in the comments:

On Windows, replace : by ;:

java -cp X.jar;. Q
like image 191
Vivien Barousse Avatar answered Sep 22 '22 14:09

Vivien Barousse