好吧,我的工作了:
基本上,你需要调用的bash与"-s"
,然后完整的命令字符串写入。
public class ShellExecutor {
private String stdinFlag;
private String shell;
public ShellExecutor(String shell, String stdinFlag)
{
this.shell = shell;
this.stdinFlag = stdinFlag;
}
public String execute(String cmdLine) throws IOException
{
StringBuilder sb = new StringBuilder();
Runtime run = Runtime.getRuntime();
System.out.println(shell);
Process pr = run.exec(cmdLine);
BufferedWriter bufWr = new BufferedWriter(
new OutputStreamWriter(pr.getOutputStream()));
bufWr.write(cmdLine);
try
{
pr.waitFor();
} catch (InterruptedException e) {}
BufferedReader buf = new BufferedReader(
new InputStreamReader(pr.getInputStream()));
String line = "";
while ((line = buf.readLine()) != null)
{
sb.append(line + "\n");
}
return sb.toString();
}
}
然后使用它是这样的:
ShellExecutor excutor = new ShellExecutor("/bin/bash", "-s");
try {
System.out.println(excutor.execute("ls/| sort -r"));
} catch (IOException e) {
e.printStackTrace();
}
显然,你有啥可做一些与错误字符串但是这是一个工作的例子。
,如果有这样的事情,因为Java是系统编程这样一个痛苦的环境下(如在文件操作谜错误条件等),我会感到惊讶。 – 2009-10-20 18:40:14