简体   繁体   中英

Running external jars using Eclipse Java project in cmd

I've written a project in eclipse and i would like to run its ".class" file using cmd .
I looked up and i saw i had to use the format :

java -cp . package.mainclass

I tried that and it kinda work, the problem is that my project have a lib directory in it that contains jar files that i use , and when running as above i get the error that classes couldn't be found (other than the main).
How can I run it ?
note : there is a xml .classpath file in the project's directory that contains the names of the jars used .

You need to add all the jars manually listed in .classpath to your Java command. Another place to find list of jars is Project->Properties->BuildPath

You can use custom scripts for generating classpath, for example (*NIX):

java -cp $(echo lib/*.jar | tr ' ' ':') package.MainClass

EDIT: Ok, so to directly use Eclipse .classpath file entries to generate classpath in *NIX, you can use following:

java -cp $(echo $(grep ".jar" .classpath | awk -F \" '{print $4}') | tr ' ' ':') package.MainClass

This way you don't have to manually generate classpath. For Windows you would require bash script for doing same, I haven't worked that out yet!

Add the libraries that your application uses to the class path.

java -cp .;lib/my-lib1.jar;lib/my-lib2.jar my.pkg.MainClass

If you also package your classes into a JAR file (which is recommended), you can do the following (assuming the name is main.jar and it is located in the application's root directory):

java -cp main.jar;lib/my-lib1.jar;lib/my-lib2.jar my.pkg.MainClass

But if you already have a JAR file for your application, you will have a manifest file , where you can add the class path to:

Class-Path: lib/my-lib1.jar;lib/my-lib2.jar

In that case, you just start it with

java -cp main.jar my.pkg.MainClass

And - last step - as you already have a main JAR with a manifest file, you can make it a runnable JAR by adding this to your manifest file:

Main-Class: my.pkg.MainClass

Now you can start your application by:

java -jar main.jar

A double-click also works now.

使用这个,我希望这对您有用:

java -cp <your jar file location> package.mainclass 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM