2

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?

Community
  • 1
  • 1
user3663882
  • 6,957
  • 10
  • 51
  • 92
  • You need to be three directories above where you are now, and run `java com.server.main.Main` because the name of the package is part of the name of the class. You also need to get yourself a basic Java book or online tutorial. – Dawood ibn Kareem Nov 09 '14 at 06:04
  • @DavidWallace exactly. Tahnk you – user3663882 Nov 09 '14 at 06:06
  • Could you give that as an answer? – user3663882 Nov 09 '14 at 06:07
  • 1
    Why would I bother? After I posted my comment, two other people posted roughly the same information as an answer. I don't see any point in adding a third almost-identical answer. If you want to accept an answer, pick one of the two at random. – Dawood ibn Kareem Nov 09 '14 at 06:09

3 Answers3

2

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
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

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
SMA
  • 36,381
  • 8
  • 49
  • 73
-1

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.

kuba44
  • 1,838
  • 9
  • 34
  • 62