Running an executable jar file built from a gradle based project

Viewed 46365

I have a standalone project which is gradle based. When I do gradle build, the jar is generated under build/libs. How do I run this executable jar from command line? I tried : java -cp build/libs/foo.jar full.package.classname but I get noClassFoundException for the classes that were imported. How do I include dependent jars as part of classpath?

6 Answers

Add a simple task to run jar

task runJar(type: JavaExec) {
    main = "-jar";
    args jar.archivePath
}

UPDATE: jar.archivePath is now deprecated, you can use jar.archiveFile.get()

task runJar(type: JavaExec) {
    main = "-jar";
    args jar.archiveFile.get()
}

I am a newbie, so my explanations here will be simplistic. My build.gradle file contains only one line: apply plugin: 'java'. I have a hello world java code in src/main/java/org/dx/test/App.java. From the command shell, I typed: gradle build. And then I saw this jar file magically created:

build/libs/helloworld.jar

All of the above answers did not work. What worked for me is:

java -cp build/libs/helloworld.jar org.dx.test.App

Now, I know gradle is full of sorcercy so I am sure my situation may not fully reflect your situation. The actions are did were:

  1. Create that one line build.gradle file
  2. Create the App.java under the doctor's prescribed folder location
  3. Type gradle build

To run a jar in terminal, first build a jar using "gradle clean build" then , navigate to -> build -> distribution -> unzip <filename>.zip file -> cd to unzipped file -> cd bin there will be 2 files - projectname & <projectname.bat> run the jar with ./projectname

If there are some args to be passed to main method use : run the jar with ./projectname params

Related