Java 在jar文件中执行shell脚本。如何提取?

Java 在jar文件中执行shell脚本。如何提取?,java,shell,Java,Shell,我正在开发一个只支持Linux的Java应用程序,我需要在其中执行一个shell脚本。根据我所读到的,执行shell脚本的唯一方法是从jar文件中提取它并执行它。问题是什么?如何在运行时提取该shell脚本 提前感谢您Unix不知道如何在jar文件中运行脚本。您必须使用给定的内容创建一个文件(运行时中有创建临时文件的例程),然后运行该文件-有关说明,请参阅。完成后,将其从文件系统中删除。我今天发现了这个问题。。。我认为有一个更好的答案: 解压-p JARFILE SCRIPTFILE | bas

我正在开发一个只支持Linux的Java应用程序,我需要在其中执行一个shell脚本。根据我所读到的,执行shell脚本的唯一方法是从jar文件中提取它并执行它。问题是什么?如何在运行时提取该shell脚本


提前感谢您

Unix不知道如何在jar文件中运行脚本。您必须使用给定的内容创建一个文件(运行时中有创建临时文件的例程),然后运行该文件-有关说明,请参阅。完成后,将其从文件系统中删除。

我今天发现了这个问题。。。我认为有一个更好的答案:

解压-p JARFILE SCRIPTFILE | bash

我应该这样做。 其中JARFILE是指向jar文件的路径 SCRIPTFILE是要执行的脚本文件的jar内的路径


这将把文件提取到stdout,然后通过管道传输到shell(bash)

首先不要将脚本捆绑到jar中。将脚本作为独立文件进行部署。

如前所述,您可以将捆绑资源中的内容复制到临时位置,执行脚本,然后删除临时位置中的脚本

下面是执行此操作的代码。请注意,我正在使用库


建议副本的可能副本不处理提取,但无法撤消关闭请求。这是JVM之外最简单的方法。
// 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();