Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to excute java.class in any folder?

Tags:

java

javac

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?

like image 426
bytefish Avatar asked Mar 04 '23 11:03

bytefish


2 Answers

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.

like image 51
Naligator Avatar answered Mar 16 '23 21:03

Naligator


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
like image 39
Roland Illig Avatar answered Mar 16 '23 21:03

Roland Illig