Executing a shell script inside a jar file. How to extract?
I am developing a Linux-only Java application, and I need to execute a shell script in it. According to what I have read, the only way to execute that shell script is by extracting it from the jar file and executing it. Th开发者_StackOverflowe question is? How can I extract that shell script at runtime?
Thank you in advance
Unix does not know how to run scripts inside jar files. You must create a file (there are routines to create temporary files in the runtime) with the given content and then run that file - see How to run Unix shell script from Java code? for instructions. When done, delete it from the filesystem.
I found this question today ... i think there is a better answer:
unzip -p JARFILE SCRIPTFILE | bash
should do it. where JARFILE is the path to the jar file and SCRIPTFILE is the path WITHIN the jar of the script file to execute.
this will extract the file to stdout which is then piped to the shell (bash)
As someone has mentioned before, you can copy the content in the bundle resource to a temp location, execute the script, and remove the script in the temp location.
Here is the code to do that. Note that I am using Google Guava library.
// Read the bundled script as string
String bundledScript = CharStreams.toString(
new InputStreamReader(getClass().getResourceAsStream("/bundled_script_path.sh"), Charsets.UTF_8));
// Create a temp file with uuid appended to the name just to be safe
File tempFile = File.createTempFile("script_" + UUID.randomUUID().toString(), ".sh");
// Write the string to temp file
Files.write(bundledScript, tempFile, Charsets.UTF_8);
String execScript = "/bin/sh " + tempFile.getAbsolutePath();
// Execute the script
Process p = Runtime.getRuntime().exec(execScript);
// Output stream is the input to the subprocess
OutputStream outputStream = p.getOutputStream();
if (outputStream != null) {
outputStream.close();
}
// Input stream is the normal output of the subprocess
InputStream inputStream = p.getInputStream();
if (inputStream != null) {
// You can use the input stream to log your output here.
inputStream.close();
}
// Error stream is the error output of the subprocess
InputStream errorStream = p.getErrorStream();
if (errorStream != null) {
// You can use the input stream to log your error output here.
errorStream.close();
}
// Remove the temp file from disk
tempFile.delete();
Do not bundle the script in your jar in the first place. Deploy the scripts as independent files.
精彩评论