简体   繁体   English

在没有CD的OS X Terminal中编译Java代码

[英]Compiling java code in OS X Terminal without cd

When I run 当我跑步

javac 'path/to/test.java'
java 'path/to/test'

I get an error like this 我收到这样的错误

Exception in thread "main" java.lang.NoClassDefFoundError: path/to/test (wrong name: test)

It works when I do the same after I run "cd path/to", but is there a way to do this without the cd command? 当我运行“ cd path / to”后执行相同操作时,它可以工作,但是没有cd命令,有没有办法做到这一点? If so, how? 如果是这样,怎么办?

Your Test.java file should have a package line at the top: 您的Test.java文件的顶部应该有一个package行:

package path.to;

public class Test {

    public static void main(String argv[]) {
    }
}

Then you can compile and run it. 然后,您可以编译并运行它。 It works on my MacBook Pro. 它可以在我的MacBook Pro上使用。 Note that java path.to.Test and java path/to/Test are equivalent . 请注意, java path.to.Testjava path/to/Test等效的

% javac path/to/Test.java
% java path.to.Test

If you are missing the package statement, then you will get the error that you are reporting. 如果缺少 package语句,那么您将得到报告的错误。

% javac path/to/Test.java
% java path.to.Test
Exception in thread "main" java.lang.NoClassDefFoundError: path/to/Test (wrong name: Test)

If you wish to compile and run the class from your current location (presumably a project directory), I would recommend: 如果您希望从当前位置(大概是项目目录)编译并运行该类,我建议:

  1. Use a package declaration in your class: 在类中使用包声明:

     package path.to; public class Test { public static void main(String[] args) { System.out.println("LOADED"); } } 
  2. When you run your code do so with dot notation to the class name: 在运行代码时,请对类名使用点符号:

     javac path/to/Test.java java path.to.Test 

Assuming test.java does not have a package statement, your class (which should be named Test , not test ) is in the unnamed package, so do this: 假设test.java没有package语句,则您的类(应命名为Test ,而不是test )位于未命名的包中,因此请执行以下操作:

javac 'path/to/test.java'
java -cp 'path/to' test

If your test.java file starts with a package to; 如果您的test.java文件以package to;开头package to; statement, then you do this: 语句,然后执行此操作:

java -cp 'path' to.test

And if it says package path.to; 如果它说package path.to; , then you do this: ,那么您可以这样做:

java path.to.test

or this to be explicit: 或明确地说:

java -cp . path.to.test

If your package statement says any other name, then your directory structure is wrong, since the directory must match the package statement, starting at the directory named in the classpath ( -cp ). 如果您的package语句使用任何其他名称,则您的目录结构不正确,因为该目录必须与package语句匹配,并从类路径( -cp )中命名的目录开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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