简体   繁体   中英

java relative path vs absolute path on command line

Running into an interesting problem When I run:

$cd /projects/MyProject/
$java -cp . S3Sample

This works fine. However if I run:

$java -cp /projects/MyProject /projects/MyProject/S3Sample
Error: Could not find or load main class .projects.MyProject.S3Sample

Why is that. Did a quick look and can't find the answer. Thanks!

I have this folder structure:

- home
  - org
    - test
      + Foo.java
      + Foo.class

And the code in Foo.java is a simple hello world application:

//Note the usage of the package statement here.
package org.test;

public class Foo {
    public static void main(String[] args) {
          System.out.println("Hello world");
    }
}

Then, in command line, in order to execute Foo.class, I should provide the complete name of the class (I'm in "/home" folder in cmd):

$ java -cp "org/test;." Foo
Exception in thread "main" java.lang.NoClassDefFoundError: Foo (wrong name: org/test/Foo)
$ java -cp "org/test;." org.test.Foo
Hello world

Now, I edit the class above and remove the package sentence:

//no package specified
public class Foo {
    public static void main(String[] args) {
          System.out.println("Hello world");
    }
}

After recompiling the class and executing the same command lines:

$ java -cp "org/test;." Foo
Hello world
$ java -cp "org/test;." org.test.Foo
Exception in thread "main" java.lang.NoClassDefFoundError: org/test/Foo (wrong name: Foo)

TL;DR

Make sure to always specify the full name of the class. Check if your class belongs to a package. Specifying the path of the class to execute is the same as writing the full name of the class, java program will replace / by . .

You should run

$ java -cp /projects/MyProject S3Sample

The path for class is already CLASSPATH-relative

With java , you specify the fully qualified name of a class containing the main method you want executed. (The launcher will replace / with . ). This class needs to be in the classpath. The argument is not a path to a file.

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