0

So I'm still a noob in Java and I'm experimenting around with a few things.

I recently created a .jar file for my class using jar cvf <name>.jar <source files> and then used that jar to compile my driver class (javac -cp <name>.jar Driver.java) though how do I now run that class using the jar?

I've tried the following 2 commands:
java Driver and,
java -cp <name>.jar Driver.

The first gives me a NoClassDefFoundError for the class used, whereas the latter just gave me a single line error.

Error: Could not find or load man class Driver

What am I doing wrong? Is it possible I'm confusing this for something else?
I'm trying to do as much as I can without the use of any IDE.

7
  • Does your Driver class contain the main method? Commented May 6, 2015 at 9:56
  • @Kayaman yes. I've initialized everything correctly as well. Commented May 6, 2015 at 9:57
  • Driver is in a package ? Commented May 6, 2015 at 9:57
  • Uh, did you compile the class before you put it in the jar? Commented May 6, 2015 at 9:59
  • 1
    So you have a jar of classes and a class outside of the jar, and you wish to run the class that is outside of the jar file? If so, see tomasz77's answer. Replace classes with the directory your Driver.class is in, and if you're on Linux, use : instead of ; as the separator. Commented May 6, 2015 at 10:04

2 Answers 2

2

You should put jar file and compiler output into classpath and specify main class:

java -classpath "<name.jar>;classes" Driver 

EDIT (thanks to Kayaman): If you are running command from linux/unix you have to use ":" as separator (in Windows works ";"). "classes" is a path to folder containing compiler output.

Sign up to request clarification or add additional context in comments.

Comments

0

When creating an executable jar ( jar which contain a class with the main method) you should tell the jar which is the mainClass to be executed and for that you should create a file called 'Manifest.mf'.

The file should contain this:

Main-Class: MyPackage.MyClass 

And when creating the jar you should use this to include your manifest:

jar cfm MyJar.jar Manifest.mf MyPackage/*.class 

And for launching your jar :

java -jar MyJar.jar 

1 Comment

Not an executable jar. Probably should have clarified.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.