user3663882
user3663882

Reputation: 7367

Error: Could not find or load main class Main

I've the java class:

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.

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?

Upvotes: 2

Views: 11925

Answers (3)

kuba44
kuba44

Reputation: 1878

Look here: 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.

Upvotes: -1

SMA
SMA

Reputation: 37103

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:

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

Use:

java -cp C:\Users\workspace\Tests\src com.server.main.Main

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201537

Your Main is in a package, I believe you need

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

set CLASSPATH=C:\Users\workspace\Tests\src
java com.server.main.Main

Upvotes: 2

Related Questions