Frage

I have a doubt about -cp and when should I use it. This is my scenario: I have two .java, the first one:

package autos.tests.paquete;

public class MainAutos {

public static void main(String args[]) {

int x = Integer.parseInt(args[0]);

Respotar objeto1 = new Respotar (x);


int mostrar = objeto1.repostar();


System.out.println(mostrar);

} }

And the second one:

package autos.tests.paquete;

public class Respotar {

int gasolina;

public Respotar (int gasolina) {

    this.gasolina=gasolina;

}


public int repostar (){

    int gasolina = this.gasolina +20;



    return  gasolina;
}

}

Well, I am at root directory, and there, I have that directory: autos/tests/paquete with both .java.

So I compile: javac autos/tests/paquete/*.java

And execute from root directory: java autos.tests.paquete.MainAutos 10 And it works, now here go my doubts:

1) I execute with java -cp . autos.tests.paquete.Main autos 10 and the behaviour is the same.

2) I move the Respotar.class from auto/tests/paquete to another directory, I compile with java autos.tests.paquete.MainAutos 10 and it works.

3) I move the MainAutos.class from auto/tests/paquete to another directory, I compile with java autos.tests.paquete.MainAutos 10 and it says: Error: Could not find or load main class autos.tests.paquete.MainAutos

4) I compile with java -cp . autos.tests.paquete.MainAutos (I have the .class on the current directory I am compiling, so I think I have to use -cp .) and it says the same: Error: Could not find or load main class autos.tests.paquete.MainAutos

Thank you in advance, I hope someone can enlighten me, regards

War es hilfreich?

Lösung

java -cp is used to set any libraries such as jar file to your current classpath.

For the examples you have shown, you can do it in the below simple way

From you root directory compile your java files using the below command

javac -d . *.java

This would created those appropriate packages and place the class files under them

Then run you code using the command like this from the same root location

java autos.tests.paquete.MainAutos
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top