Matthew Moisen
Matthew Moisen

Reputation: 18299

How to Run a Java Class File from the Command Line that was Compiled by Eclipse? External Jar problems

I have a project that runs fine in Eclipse. The project uses many external jars. My file directory for the project has a bin and src directory, and a .classpath and .project files.

From this directory, if I execute:

java -cp bin com.brm.main.Demo2    

I receive the following error:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/lucene/sea
rch/Query
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2442)
    at java.lang.Class.getMethod0(Class.java:2685)
    at java.lang.Class.getMethod(Class.java:1620)
    at sun.launcher.LauncherHelper.getMainMethod(LauncherHelper.java:494)
    at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:486)

Caused by: java.lang.ClassNotFoundException: org.apache.lucene.search.Query
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    ... 6 more

org/apache/lucene is an external jar.

Upvotes: 4

Views: 9157

Answers (2)

rob
rob

Reputation: 6247

You also need to include your other dependencies on the classpath, separating classpath elements with ; on Windows or : on Linux.

On Windows:

java -cp bin;path\to\lucene.jar com.brm.main.Demo2

On Linux:

java -cp bin:path/to/lucene.jar com.brm.main.Demo2

If you have other jarfiles or directories in addition to lucene and bin, you'll have to add those, too.

If you're trying to deploy your program, a better solution is to use Eclipse's "Export" wizard to export a Runnable JAR File, which will walk you through the steps to select your main class and bundle your dependencies. Or, going even further, you can use ant or maven to build your project and create a deployable bundle.

Upvotes: 3

Rahul Tripathi
Rahul Tripathi

Reputation: 172518

How about trying like this:-

java -cp .;%CLASSPATH% com.brm.main.Demo2

seems like your classpath is invalid and because of that the .jars for the external libraries are not found.

Upvotes: 2

Related Questions