简体   繁体   中英

Compiling and running Java from the command line

I created the below project structure.

[~/Projects/CountWords]@Ubuntu1804  #> find .
.
./bin
./src
./src/main
./src/main/java
./src/main/java/App.java

This is App.java content :

package src.main.java;


public class App {
    public static void main(String[] args){
        System.out.println("Hola");
    }
}

I compile my app as :

javac -d bin/ -cp src/main/java/ src/main/java/*

Which works fine. I am using an asterisk because I'll have more classes in that folder but I have only that one for now. This creates the following structure :

[~/Projects/CountWords]@Ubuntu1804  #> find .
.
./bin
./bin/src
./bin/src/main
./bin/src/main/java
./bin/src/main/java/App.class
./src
./src/main
./src/main/java
./src/main/java/App.java

But my problem is when I try to run the app. I assumed this would work :

java src.main.java.App

But this fails with :

Error: Could not find or load main class src.main.java.App
Caused by: java.lang.ClassNotFoundException: src.main.java.App

What am I doing wrong?

I know that it must be a very silly question, but I want to code a small/medium project by hand just to understand what the IDE does on its own. After working with Java for a while using Eclipse, I noticed I had no idea how to do this by hand and I want to change that.

You have to define class path for java. There are two possibilites:

run

java -cp ./bin src.main.java.App

or change to bin directory and then run without cp

cd bin 
java src.main.java.App

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM