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?
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.
When you run java -help
, you get this output:
Usage: java [options] <mainclass> [args...]
(to execute a class)
...
This short message says <mainclass>
, and by that it means "the fully qualified name of the Java class, regardless of where it is saved in the file system".
When you run java src.Main
or java src/Main
, you tell the java
command to run the class src.Main
, which doesn't exist anywhere in the classpath.
To fix this, set the classpath to src
(since that's where the .class
files are), and then run the class called Main
:
java -classpath src/ Main
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With