Search code examples
javaeclipsebatch-filejardom4j

NoClassDefFoundError: org/dom4j/io/SAXReader


I've currently imported the following

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

I'm running the program with the help of a BATCH file but it's throwing the following errors -

C:\AISHU\WEB SERVICES>java  -jar webservices.jar
C:\AISHU\TEST FOLDER\formteest\fulltestxsd.xsd
Exception in thread "main" java.lang.NoClassDefFoundError:org/dom4j/io/SAXReader
        at XsdToXmlActual.main(XsdToXmlActual.java:29)
Caused by: java.lang.ClassNotFoundException: org.dom4j.io.SAXReader
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 1 more

C:\AISHU\WEB SERVICES>pause
Press any key to continue . . .

But it's working perfectly fine when I run it in Eclipse. I've added it as an external JAR while configuring the build path . So, in the .classpath file the location to already exists.

<classpathentry kind="lib" path="C:/Users/Aishu/Downloads/dom4j-1.6.1.jar"/>
<classpathentry kind="lib" path="C:/Users/Aishu/Downloads/jaxen-1.1-beta-6.jar"/>

I've tried reinstalling dom4j but it still results in the same error.I've been stuck at this for hours, any help is highly appreciated.


Solution

  • When you run a program with the -jar option, you run it as an executable jar. The rules for resolving the classpath are different in that case. Java will ignore the -cp and -classpath options and the CLASSPATH environment variable, and it will only look at the classpath defined in the manifest file of the jar.

    You have to put the necessary jar files in the classpath in the manifest file. The manifest file should look like this:

    Manifest-Version: 1.0
    Main-Class: XsdToXmlActual
    Class-Path: dom4j-1.6.1.jar jaxen-1.1-beta-6.jar
    

    Put the two jar files in the same directory as your own jar file, and then run your own jar file with the -jar option:

    java -jar webservices.jar
    

    See: Adding Classes to the JAR File's Classpath