Why does my IDE find the JAR but my command line d

2019-08-30 14:32发布

This question already has an answer here:

I've tried searching around, but I couldn't find any answers that fit my case.

I can run the file CB.java just fine when I use an IDE. This file depends on classes specified in cs2.jar. Here are the contents of its directory.

02/12/2013  03:43 PM    <DIR>          .
02/12/2013  03:43 PM    <DIR>          ..
02/12/2013  03:45 PM             2,226 CB.class
02/12/2013  01:21 PM             2,164 CB.java
02/12/2013  03:43 PM            71,128 cs2.jar
               3 File(s)         75,518 bytes
               2 Dir(s)  408,977,362,944 bytes free

When I run it off my IDE, CB.java works just fine. However, when I try java CB in the command line, I get:

Exception in thread "main" java.lang.NoClassDefFoundError: sn/visual/JRect
angle
Caused by: java.lang.ClassNotFoundException: sn.visual.JRectangle
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        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)
Could not find the main class: CB.  Program will exit.

Furthermore, I tried following suggestions to add something to the classpath using:

>java -cp C:\Users\...blah blah blah...\Software_Engineering cs2
Exception in thread "main" java.lang.NoClassDefFoundError: cs2
Caused by: java.lang.ClassNotFoundException: cs2
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        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)
Could not find the main class: cs2.  Program will exit.

How come my IDE is smart but my command line isn't?

Thank you.

2条回答
虎瘦雄心在
2楼-- · 2019-08-30 15:10

The class path is set to just consider .class files in the given directory. You need to add the jar file to the class path: java -cp C:\somewhere\cs2.jar

查看更多
该账号已被封号
3楼-- · 2019-08-30 15:19

How come my IDE is smart but my command line isn't?

I suspect in your IDE, you've included the jar file in your build path, so it then includes it when both building and running. (You haven't told us which IDE it is, so it's hard to use the exact terminology it would use)

On the command line, you need to specify the jar file when both building and running too, so you'd use:

To build:

javac -cp cs2.jar CB

To run:

java -cp .;cs2.jar CB
查看更多
登录 后发表回答