简体   繁体   中英

Able to run java program from IntelliJ but not from command line

I am working on a project. I am able to run the program from within IntelliJ but when I try to run it using

java -cp <my jar> <Main class>

I get a java.lang.NoClassDefFoundError

Exception in thread "main" java.lang.NoClassDefFoundError: org/nocrala/tools/gis/data/esri/shapefile/ValidationPreferences
    at Converter2.parse(Converter2.java:26)
    at Main.main(Main.java:19)
Caused by: java.lang.ClassNotFoundException: org.nocrala.tools.gis.data.esri.shapefile.ValidationPreferences
    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:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)

How can I fix this?

May I ask what is your exact <Main class> ? Also how did you pack the jar? Maybe you didn't include all the dependency jar libraries? (maybe in this case nocrala)?

It looks like Main.main() is already executing.

I did a jar xf on my jar file and it only showed me .classes for the .java files that I had written. That gave me a hint. Basically mvn package did not package the dependencies into the jar file. I searched a bit and found this link on how to package dependencies into jar . I edited my pom.xml and pasted following code in it (directly taken from the aforementioned link)

<build>
    <plugins>
      <!-- any other plugins -->
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
      </plugin>
    </plugins>
  </build>

now when I ran mvn package it generated a foo-jar-with-dependencies.jar and I was able to execute it successfully from the command line using java -cp ... . I also did jar xf on it and verified it now contained all my dependencies. The difference in file size was also enormous as I was pulling in lot of third party packages in my project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM