【发布时间】:2010-10-11 05:16:34
【问题描述】:
我尝试了许多不同的示例,但都不起作用。
我非常感谢一些示例 Java 代码来运行 shell 脚本。
【问题讨论】:
-
????你能说得更清楚些吗?
-
多一点上下文会很好,是的。
我尝试了许多不同的示例,但都不起作用。
我非常感谢一些示例 Java 代码来运行 shell 脚本。
【问题讨论】:
您需要 Runtime.getRuntime().exec(...)。请参阅a very extensive example(不要忘记阅读前三页)。
请记住,Runtime.exec 不是外壳;如果你想执行一个 shell 脚本,你的命令行应该是这样的
/bin/bash scriptname
也就是说,您需要的 shell 二进制文件是完全限定的(尽管我怀疑 /bin 总是在路径中)。你不能假设如果
myshell> foo.sh
运行,
Runtime.getRuntime.exec("foo.sh");
也像在第一个示例中已经在运行的 shell 中一样运行,但不在 Runtime.exec 中。
一个经过测试的示例(Works on My Linux Machine(TM)),大部分来自the previously mentioned article:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ShellScriptExecutor {
static class StreamGobbler extends Thread {
InputStream is;
String type;
StreamGobbler(InputStream is, String type) {
this.is = is;
this.type = type;
}
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null)
System.out.println(type + ">" + line);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("USAGE: java ShellScriptExecutor script");
System.exit(1);
}
try {
String osName = System.getProperty("os.name");
String[] cmd = new String[2];
cmd[0] = "/bin/sh"; // should exist on all POSIX systems
cmd[1] = args[0];
Runtime rt = Runtime.getRuntime();
System.out.println("Execing " + cmd[0] + " " + cmd[1] );
Process proc = rt.exec(cmd);
// any error message?
StreamGobbler errorGobbler = new StreamGobbler(proc
.getErrorStream(), "ERROR");
// any output?
StreamGobbler outputGobbler = new StreamGobbler(proc
.getInputStream(), "OUTPUT");
// kick them off
errorGobbler.start();
outputGobbler.start();
// any error???
int exitVal = proc.waitFor();
System.out.println("ExitValue: " + exitVal);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
【讨论】:
Shell 脚本 test.sh 代码
#!/bin/sh
echo "good"
执行shell脚本test.sh的Java代码
try {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(new String[]{"/bin/sh", "./test.sh"});
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while ((line = input.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
【讨论】: