tags:

views:

78

answers:

2

I'm puzzled by the process of running java programs, maybe you can help.

I have several .java files in ~/working_dir/org/project/ that have main functions, and I want to package them in a jar to run them. I do:

cd ~/working_dir/org/projectname
javac -classpath $CLASSPATH *.java
cd ~/working_dir/
jar cf myjar.jar org/

And then try to run one of the classes in the jar by doing: java -cp myjar.jar org.project.SomeClass

and get

Exception in thread "main" java.lang.NoClassDefFoundError: org/project/SomeClass
Could not find the main class: org.project.SomeClass

What do I do wrong? The classes compile without any errors, and jar tf myjar.jar shows that they're indeed there. As far as I know I don't need to create a Manifest file because I provide the class from which I want to run the main function at runtime - or am I wrong here?

Help much appreciated!

A: 

If the exploded jar org/project/SomeClass is beneath your current working dir:

/  <- you are here
+---/org
    |
    +-----/project
          |
          +--------SomeClass.class

try java -cp . org.project.SomeClass instead

jskaggz
A: 

First of all, note that if you simply do

javac org/project/SomeClass.java

the class file will end up right beside the .java file which makes it tricky to include only .class-files in the jar. I suggest you use the -d option to specify destination directory:

javac -d bin org/project/SomeClass.java

Have a look at the following bash-session for details to get it working:

A listing of the source directory:

user@host:/working_dir/src$ ls -R
.:
org

./org:
projectname

./org/projectname:
SomeClass.java

The SomeClass.java file:

user@host:/working_dir/src$ cat org/projectname/SomeClass.java 
package org.project;

public class SomeClass {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}

Compile it (with target directory ../bin)

user@host:/working_dir/src$ javac org/projectname/SomeClass.java -d ../bin

List the result and make sure you got the directories right:

user@host:/working_dir/src$ cd ../bin/
user@host:/working_dir/bin$ ls -R
.:
org

./org:
project

./org/project:
SomeClass.class

Create the jar file:

user@host:/working_dir/bin$ jar cf myjar.jar org

Make sure you got the directories right and didn't accidentally include the "bin" directory:

user@host:/working_dir/bin$ jar tf myjar.jar 
META-INF/
META-INF/MANIFEST.MF
org/
org/project/
org/project/SomeClass.class

Launch the main method:

user@host:/working_dir/bin$ java -cp myjar.jar org.project.SomeClass 
Hello World

user@host:/working_dir/bin$ 
aioobe
Thanks for the detailed instructions. This is pretty much what I thought I did before (with the exception of not having a separate bin/ folder), but this time it worked - I must've made some small but crucial mistake the first time.
R.C.