问题
This question has been asked before but I still cannot figure whats wrong for some reason. I got a class named NewClass in package syntaxtest in file src. From src path I type :
javac src/syntaxtest/NewClass.java
and the class is compiled and I can see NewClass.class in syntaxtest folder. Now from that same path or even the same folder with NewClass.class, I can't figure out how to run the class from terminal. I have made many different attempts but ether I get
ClassDefNotFound or ClassDefNotFound (wrong name : syntaxtest/NewClass)
回答1:
Try "java -cp src syntaxtest.NewClass
".
That is, if you have a folder "src" which contains the subfolder (package) "syntaxtest" and the class "NewClass" is in "package syntaxtest", then the above command will work.
$ ls src/syntaxtest
NewClass.java
$ cat src/syntaxtest/NewClass.java
package syntaxtest;
public class NewClass {
public static void main(String args[]) {
System.out.println("Hello, World!");
}
}
$ javac src/syntaxtest/NewClass.java
$ java -cp src syntaxtest.NewClass
Hello, World!
回答2:
I've made the following test:
Created a java file in home/test/blah/TestClass.java
package blah;
public class TestClass { public static void main(String[] args) { System.out.println("Hello World!"); } }
Went to directory home/test/
- Compiled the file by typing:
javac blah/TestClass.java
- Got the file compiled ok.
- Ran it by typing:
java blah.TestClass
- Got the message "Hello World!" as expected: program runs ok.
- Went to directory home/
- Tried to run by typing:
java test/blah.TestClass
- ... and many other combinations of slashes and dots..... nothing worked.... keep getting the same Exception as you:
java.lang.NoClassDefFoundError
So it seems to me that to run a Java class using the command 'java' you really must be in the application's root folder.
回答3:
I had a similar problem. I wanted to organize my project using a src and bin folders directly from the Mac finder and use Emacs or some other text editor. I just didn't like eclipse.
You can't execute the classes from another folder, but you can do is compile from another folder into the one you are going to execute.
For example (assuming there is no package), move to the bin folder and run:
$ javac ../src/name.java -d ../bin/
(That compiles from the src folder and outs the .class file directly on bin)
来源:https://stackoverflow.com/questions/9234488/running-java-class-from-terminal