I have HelloWorld program in a package helloworld as:
package helloworld;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
I put this HelloWorld.java file in the package folder helloworld, which is in a folder myapp as:
C:\test\myapp>dir
Volume in drive C has no label.
Volume Serial Number is F48A-3578
Directory of C:\test\myapp
10/22/2021 07:28 PM <DIR> .
10/22/2021 07:28 PM <DIR> ..
10/22/2021 07:28 PM <DIR> helloworld
0 File(s) 0 bytes
3 Dir(s) 12,348,715,008 bytes free
C:\test\myapp>cd helloworld
C:\test\myapp\helloworld>dir
Volume in drive C has no label.
Volume Serial Number is F48A-3578
Directory of C:\test\myapp\helloworld
10/22/2021 07:28 PM <DIR> .
10/22/2021 07:28 PM <DIR> ..
10/22/2021 07:16 PM 436 HelloWorld.class
10/22/2021 07:14 PM 148 HelloWorld.java
2 File(s) 584 bytes
2 Dir(s) 12,348,715,008 bytes free
C:\test\myapp\helloworld>
In CMD (Windows), I am in a folder above the myapp folder, so, I could compile it as:
C:\test>javac myapp\helloworld\HelloWorld.java
C:\test>
But, when I tried to run it as below, it failed.
C:\test>java myapp\helloworld.HelloWorld
Error: Could not find or load main class myapp\helloworld.HelloWorld
Caused by: java.lang.NoClassDefFoundError: helloworld/HelloWorld (wrong name: myapp\helloworld/HelloWorld)
Of course, if I go into the myapp folder as below I can run it.
C:\test>cd myapp
C:\test\myapp>java helloworld.HelloWorld
Hello World
C:\test\myapp>
My question is how can I run a class file located in a subfolder which is not part of a package?
CodePudding user response:
When you run java.exe, by default the classpath is only the current folder.
When you are in the parent folder, you need to add classpath explicitly
java -cp myapp helloworld.HelloWorld
CodePudding user response:
You need to mention the classpath with java command. Please refer to this link which explains the way classpath needs to be referred
https://docs.oracle.com/javase/7/docs/technotes/tools/windows/classpath.html
So the possible command should be something like
java -classpath C:\test\myapp helloworld.HelloWorld