gpt4 book ai didi

java - 通过 Java 进程生成器执行 bash

转载 作者:行者123 更新时间:2023-12-01 08:59:05 25 4
gpt4 key购买 nike

我试图通过 JAVA 代码执行脚本,但它没有被执行。我尝试了 Process 类的 execute(),但经过一番搜索希望能够实现此目的后,我切换到 ProcessBuilder。但脚本没有被执行。

JAVA代码:

String fileName = "pkgdiff.sh";
File file = new File(fileName);
ProcessBuilder builder = new ProcessBuilder("/bin/sh", fileName);
builder.directory(file.getParentFile());
Process process = builder.start();
process.waitFor();
StringBuffer output = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
LOGGER.info("### Script Execution result --> " + fileName+"-->" + output);

脚本文件:

#!/bin/sh
.. rest of the content

最佳答案

脚本产生了多少输出?您应该在调用 waitFor() 之前处理其输出,否则如果填满了输出缓冲区,进程可能会阻塞。

来自Java API :

Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, or even deadlock.

关于java - 通过 Java 进程生成器执行 bash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41829465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com