问题
I have a Java project in Eclipse. It works fine and I can run it from cmd using java -jar sample-app.jar
I now have to use Gradle to produce an executable sh
file for use in Linux.
I've found some resources on creating start scripts but the most I've managed to do is use the standard 'startScripts' task to create a sample.app.bat file.
I've scoured question after question and page after page on google to try and find an answer and I'm not having much luck. I've also read through the Gradle Application plugin documentation a number of times and still quite confused.
How do I write a Gradle task to generate an sh
file to execute my sample-app.jar file?
Note: The sample-app.bat file does no execute. It only produces an "Error: Cannot find or load main class com.sample.MainClass
回答1:
It seems that mentioned application plugin is what you're looking for. Here you can find a little demo. Now to run main class you need to run gradle run
. To prepare sh and bat scripts run gradle gradle startScripts
. To prepare a runnable (and easily copyable) version of application and starts scripts run gradle distZip
or gradle distTar
. Both tasks will prepare and archive that can be extracted to given directory and run with prepared script. The last task gradle installDist
will prepare both script and executable jar in a given directory but without packing them.
All artifacts created with dist*
, installDist
and startScripts
can be found under build
directory. Try running:
gradle clean distZip distTar installDist
and then tree -a build
to view all prepared filed.
To run main class from the prepared jar remember to execute shell scripts in the correct directory, e.g.: build/install/lol/bin
.
回答2:
There is a standard Gradle way how to do it. You must start your gradle.build
by
apply plugin: 'application'
After that, you can launch distTar
, distZip
, and installZip
tasks. (They lie in distribution
task folder). Each of them creates the build/scripts
folder in your project and puts windows and Linux scripts there. Also, they create tar/zip/folder installation - look at the distribution
plugin.
Notice, you don't need to apply the distribution
plugin - it is in the 'application' plugin already. And the startScripts
plugin is in the distribution
plugin.
But the situation is not so nice. The second problem is that the generated scripts are bad. At least that for Windows. So, you will have to edit them by hand or automate the process in the script inserted in startScripts
. It will look so:
startScripts {
doLast {
your script editing lines here.
}
}
来源:https://stackoverflow.com/questions/41712119/how-to-generate-an-executable-sh-file-with-gradle