Reputation: 5526
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)
Upvotes: 3
Views: 30461
Reputation: 29
You need to package the class as a runnable JAR. This can be accomplished from your IDE. Then, just use the java -jar jarname.jar command to run your jar from the terminal without issues.
Upvotes: 0
Reputation: 361
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)
Upvotes: 0
Reputation: 13690
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/
javac blah/TestClass.java
java blah.TestClass
java test/blah.TestClass
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.
Upvotes: 2
Reputation: 156444
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!
Upvotes: 8