Matt
Matt

Reputation: 11317

Adding jar to classpath when running from command line

Ok I know this question has been asked many many many times before, but I've googled it and looked at examples and looked at questions on SO for the past month, and I seriously cannot get this to work. I think the problem is that I want to be able to run the program from both Eclipse and the command line. I'm also using OSX and I think a lot of the examples I'm reading are for Windows/Linux.

If I have a simple program compiled in Eclipse that I want to run from the command line I do this:

java -cp bin MyProgram

I have another program I compile and run in Eclipse, and this references the MySQL JDBC connector (mysql-connector-java-5.1.19-bin.jar) which is stored in the same directory. This works fine from Eclipse, but I can't run it from the command line.

I've tried all combinations of things...

java -classpath "bin;mysql-connector-java-5.1.19-bin.jar" MyProgram
java -cp bin\;mysql-connector-java-5.1.19-bin.jar MyProgram

and get all sorts of class not found errors...

Exception in thread "main" java.lang.NoClassDefFoundError: MyProgram
Caused by: java.lang.ClassNotFoundException: MyProgram
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)

Upvotes: 12

Views: 51117

Answers (5)

Andrew Thompson
Andrew Thompson

Reputation: 168795

See:

String pathSeparator = System.getProperty("path.separator");

Upvotes: 1

mprivat
mprivat

Reputation: 21902

Use a ':' to separate your entries on Unix systems:

java -classpath "bin:mysql-connector-java-5.1.19-bin.jar" MyProgram
java -cp bin:mysql-connector-java-5.1.19-bin.jar MyProgram

Eclipse converts it automatically.

Upvotes: 5

Johm Don
Johm Don

Reputation: 629

I would highly suggest you try --jar or -jar. I can't remember which it is, but those should settle you. Also, if you have the dev tools from apple, they have a jar packager.

Upvotes: -2

AlexR
AlexR

Reputation: 115328

Your problem is min separator you are using. Separator ; is for windows. On Unix systems you should use : instead:

java -classpath "bin:mysql-connector-java-5.1.19-bin.jar" MyProgram

Upvotes: 14

user1335794
user1335794

Reputation: 1092

you did not set your main class in classpaht, try add ./ in -cp

Upvotes: 0

Related Questions