问题是我正在运行一个 .sh 文件,其中有 3 个使用 Java 的 Runtime.exec("") 方法的命令,但只执行 .sh 文件中的第一个命令。
任何人都可以回答可能是什么问题吗?
这是我的代码。
Process process = Runtime.getRuntime().exec("run.sh");
process.waitFor();
DataInputStream d = new DataInputStream(process.getInputStream());
System.out.println(d.readLine());
System.out.println("test");
run.sh脚本如下:
#! /bin/sh
echo "start"
ls -a
echo "stop"
它执行 run.sh 但只执行第一个命令(echo 命令)。我尝试使用不同的命令,但结果保持不变。只有第一个被执行。
最佳答案
DataInputStream d = new DataInputStream(process.getInputStream()); System.out.println(d.readLine());
shell 脚本正在执行所有命令,但您只是从进程的输入流中读取第一行,其中包含 shell 脚本的所有输出。相反,阅读直到流末尾,您将看到所有命令的输出。
String output = StringUtils.join(IOUtils.readLines(process.getInputStream));
两者StringUtils和 IOUtils分别是来自 apache commons lang 和 commons IO 的实用程序类。
如果您不想使用公共(public)库,则
StringBuilder output = new StringBuilder;
String line;
while ((line = d.readLine()) != null) {
output.append(line);
}
System.out.println(output.toString());
关于Java 仅执行 .sh 文件中的第一个命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12859982/