java相对路径vs命令行上的绝对路径 [英] java relative path vs absolute path on command line

查看:158
本文介绍了java相对路径vs命令行上的绝对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遇到一个有趣的问题
当我跑步时:

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!

推荐答案

我有这个文件夹结构:

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

Foo.java中的代码是一个简单的hello world应用程序:

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");
    }
}

然后,在命令行中,为了执行Foo .class,我应该提供类的完整名称(我在cmd中的/ home文件夹中):

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

现在,我编辑上面的类并删除 package 句子:

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


TL;DR

确保始终指定全名类。检查您的类是否属于某个包。指定要执行的类的路径与写入类的全名相同, java 程序将替换 / by

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

这篇关于java相对路径vs命令行上的绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆