java relative path vs absolute path on command line

早过忘川 提交于 2019-12-22 09:50:28

问题


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!


回答1:


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 ..




回答2:


You should run

$ java -cp /projects/MyProject S3Sample

The path for class is already CLASSPATH-relative




回答3:


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.



来源:https://stackoverflow.com/questions/24266526/java-relative-path-vs-absolute-path-on-command-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!