简体   繁体   中英

Class not found when running program from command line

Here is the structure of my project:

MyProject
-lib
   -mp3agic-0.9.0.jar

-src
   -com.company
      -Main.java

Inside Main, I import the content of mp3agic:

import com.mpatric.mp3agic.*;

From MyProject, I compile the class using:

javac -cp "lib/*" src/com/company/Main.java

From MyProject/src, I try to run the program with:

java -cp. com/company/Main

and I get the following error:

Exception in thread "main" java.lang.NoClassDefFoundError: com/mpatric/mp3agic/InvalidDataException

Apparently, the jdk can not find the dependencies from the lib folder when running the class, albeit this problem doesn't occur when compiling. I guess there's a problem with the syntax of the command, but I just can't find it.

Can you please help me?

EDIT: I solved the problem, moving the lib folder under src and then running:

C:\MyProject\src>javac -cp "lib/*" com/company/Main.java

C:\MyProject\src>java -cp.;"lib/*" com/company/Main

Now, the code compiles and executes without any issue.

HOWEVER, if I leave lib under the project root, this is what happens:

C:\MyProject>javac -cp "lib/*" src/com/company/Main.java

C:\MyProject>java -cp.;"lib/*" src/com/company/Main

Error: Could not find or load main class src.com.company.Main

WHY?

java.exe -classpath {path} Main

I think you have to add classpath also and when run the program(not only compile)

You should use maven or gradle or you'll have to say which console are your using, and which operating system -if you don't know what a console is, you'll first have to google for that before messing with javac directly- But if you insist:

for Linux, OSX, any UNIX-like:

javac -cp ".:lib/mp3agic-0.9.0.jar" src/com/company/Main.java

for Windows:

javac -cp ".;lib/mp3agic-0.9.0.jar" src/com/company/Main.java

To run under windows:

java -cp.;lib\mp4agic-0.9.0.jar com.company.Main

You may need to use slash (/) instead of backslash depending of which console you're using. Or just try "/" or "\" and see what works for you.

If you still get class not found exception, then the issue is not related with classpath or java command but on your code (hard to say, without seeing the code).

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