我在 helloworld 包中有一個HelloWorld程式:
package helloworld;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
我將此HelloWorld.java檔案放在包檔案夾helloworld 中,該檔案夾位于myapp檔案夾中,如下所示:
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>
在 CMD (Windows) 中,我位于myapp檔案夾上方的檔案夾中,因此,我可以將其編譯為:
C:\test>javac myapp\helloworld\HelloWorld.java
C:\test>
但是,當我嘗試按如下方式運行它時,它失敗了。
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)
當然,如果我進入myapp檔案夾,如下所示,我可以運行它。
C:\test>cd myapp
C:\test\myapp>java helloworld.HelloWorld
Hello World
C:\test\myapp>
我的問題是如何運行位于不屬于包的子檔案夾中的類檔案?
uj5u.com熱心網友回復:
運行 java.exe 時,默認情況下類路徑僅為當前檔案夾。
當你在父檔案夾時,需要顯式添加classpath
java -cp myapp helloworld.HelloWorld
uj5u.com熱心網友回復:
您需要使用 java 命令提及類路徑。請參閱此鏈接,該鏈接解釋了需要參考類路徑的方式
https://docs.oracle.com/javase/7/docs/technotes/tools/windows/classpath.html
所以可能的命令應該是這樣的
java -classpath C:\test\myapp helloworld.HelloWorld
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/334152.html
上一篇:Flutter類屬性(基礎)
