java 错误:无法找到或加载主类 Main
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26825497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error: Could not find or load main class Main
提问by user3663882
I've the java class:
我有java类:
package com.server.main;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
public static void main(String args[]) throws Exception{
ServerSocket server = new ServerSocket(12345);
Socket client = server.accept();
PrintWriter writer = new PrintWriter(client.getOutputStream());
writer.write("Hello from server");
}
}
Now I'm trying to compile and run it. What I do is:
现在我正在尝试编译并运行它。我要做的是:
javac Main.java
It's OK, Main.class
is produced.
没关系,Main.class
生产了。
Now, according to that post, I was trying to run that program:
现在,根据那篇文章,我试图运行该程序:
java -cp C:\Users\workspace\Tests\src\com\server\main Main
java -cp C:\Users\workspace\Tests\src\com\server\main Main.class
java -cp . Main
java -cp . Main.class
All these produce the output:
所有这些都会产生输出:
Error: Could not find or load main class Main
What's wrong?
怎么了?
采纳答案by Elliott Frisch
Your Main
is in a package, I believe you need
你Main
在一个包裹里,我相信你需要
java -cp C:\Users\workspace\Tests\src com.server.main.Main
You might also move to the top folder of your project and use .
like
您也可以移动到项目的顶部文件夹并使用.
类似
cd C:\Users\workspace\Tests\src
java -cp . com.server.main.Main
Finally, you could add that folder to your CLASSPATH
like
最后,您可以将该文件夹添加到您CLASSPATH
喜欢的文件夹中
set CLASSPATH=C:\Users\workspace\Tests\src
java com.server.main.Main
回答by SMA
You need to refer from one level above the package directory that you are using. So your package here is com.server.main which means your directory structure is:
您需要从您正在使用的包目录上方的一级进行引用。所以你这里的包是 com.server.main 这意味着你的目录结构是:
src/
com/
server/
main/
Main.java
Main.class
You don't necessarily need to be at src directory (that's the reason we use -cp or -classpath option) and give the following command
您不一定需要在 src 目录(这就是我们使用 -cp 或 -classpath 选项的原因)并提供以下命令
Use:
利用:
java -cp C:\Users\workspace\Tests\src com.server.main.Main
回答by kuba44
Look here: http://docs.oracle.com/javase/tutorial/getStarted/problems/index.html
看这里:http: //docs.oracle.com/javase/tutorial/getStarted/problems/index.html
I find there answer to my problem with compile and run java application in terminal.
我找到了在终端中编译和运行 java 应用程序的问题的答案。