我有一个普通的Java应用程序,该应用程序的主类调用src/main/resources/*.sh下的shell脚本文件。

我正在使用Runtime.getRuntime()。exec(cmd)执行脚本。

String cmdPath = new this.getClass().getResource("/XXXX.sh").getPath()
String[] cmd = { "bash", cmdPath };


我收到退出代码127。

1)使用java -jar xxx.jar运行

2)sh文件的文件权限为-rw-rw-r--

如何获得脚本文件的文件许可权才能执行?

脚本文件位于src / main / resource /

使用maven-jar插件捆绑jar,脚本文件进入根目录


/ -com
 -软件
 -cmd.sh

尝试使用具有自定义脚本的maven程序集插件向{basedir}(未在任何地方定义)下的所有文件授予755权限。它不起作用

<assembly
        xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
    <id>ourAssembly</id>
    <formats>
        <format>jar</format>
    </formats>

    <fileSets>
        <fileSet>
            <directory>${basedir}</directory>
            <includes>
                <include>**/*</include>
            </includes>
            <fileMode>0755</fileMode>
        </fileSet>
    </fileSets>

最佳答案

URL的getPath()方法未返回有效的文件名。 URL的“路径”仅是授权之后的部分,不包括任何查询或片段。 URL中不允许使用许多字符,因此将它们转义百分号,并且getPath()将返回带有这些转义符的字符串。

此外,.jar条目根本不是文件,它只是.jar文件中代表压缩数据的字节的子序列。要执行它,您需要将其复制到真实文件中并执行。

像这样:

Path script = Files.createTempFile(null, ".sh",
    PosixFilePermissions.asFileAttribute(
        PosixFilePermissions.fromString("rw-rw-r--")));

try (InputStream embeddedScript =
    this.getClass().getResourceAsStream("/XXXX.sh")) {

    Files.copy(embeddedScript, script, StandardCopyOption.REPLACE_EXISTING);
}

String[] cmd = { "bash", script.toString() };


完成操作后,您应该删除副本:

ProcessBuilder builder = new ProcessBuilder(cmd);
builder.inheritIO();

Process process = builder.start();
process.waitFor();

Files.delete(script);

08-06 02:27