Search code examples
javajavac

How to excute java.class in any folder?


This is my folder:

$ tree
.

├── src
│   ├── Main.class
│   ├── Main.java
│   └── xyz
│       └── bitfish
│           ├── Fish.class
│           └── Fish.java

if I try to excute Main.class in current folder, it will fail:

$java src/Main
Error: Could not find or load main class src.Main
Caused by: java.lang.NoClassDefFoundError: Main (wrong name: src/Main)

$ java src.Main
Error: Could not find or load main class src.Main
Caused by: java.lang.NoClassDefFoundError: Main (wrong name: src/Main)

But if I try to do this in src folder, it will be fine

$ cd src
src$ java Main
// it works

What is the problem? How to excute Main.class in any foler?


Solution

  • try using the command:

    java -classpath src Main

    when you give the command

    java src/Main --> then java not only tries to use the class in src folder; but it also assumes that the package is src.Main ; and so trying to execute it that way will give you an error; unless the class defined by Main.java --> Main.class is in package "src" apart from being in directory src.