我希望我的 Java程序执行bash脚本并将输出返回给Java.诀窍是我的脚本启动某种“交互式会话”,我想这就是我的Java应用程序冻结的原因(我猜想会进入无限循环).这是我用来执行脚本的代码,我使用ProcessBuilder来执行此操作.我也试过了
Runtime.getRuntime().exec(PathToScript);
它也不起作用.
public class test1 {
public static void main(String a[]) throws InterruptedException, IOException {
List<String> commands = new ArrayList<String>();
List<String> commands1 = new ArrayList<String>();
commands.add("/Path/To/Script/skrypt3.sh");
commands.add("> /dev/ttys002");
ProcessBuilder pb = new ProcessBuilder(commands);
pb.redirectErrorStream(true);
try {
Process prs = pb.start();
Thread inThread = new Thread(new In(prs.getInputStream()));
inThread.start();
Thread.sleep(1000);
OutputStream writeTo = prs.getOutputStream();
writeTo.write("oops\n".getBytes());
writeTo.flush();
writeTo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class In implements Runnable {
private InputStream is;
public In(InputStream is) {
this.is = is;
}
@Override
public void run() {
try {
byte[] b = new byte[1024];
int size = 0;
while ((size = is.read(b)) != -1) {
System.out.println(new String(b));
}
is.close();
} catch (IOException ex) {
Logger.getLogger(In.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
这是我尝试执行的脚本.当我直接从终端运行它时,它就像一个魅力.
#!/bin/bash
drozer console connect << EOF > /dev/ttys002
permissions
run app.package.info -a com.mwr.example.sieve
exit
EOF
最佳答案 您不应该尝试添加重定向指令作为命令名称的一部分:
commands.add("/Path/To/Script/skrypt3.sh");
commands.add("> /dev/ttys002");
ProcessBuilder pb = new ProcessBuilder(commands);
相反,使用redirectOutput方法,如下所示:
tty = new File("/dev/ttys002");
ProcessBuilder pb = new ProcessBuilder("/Path/To/Script/skrypt3.sh")
.redirectOutput(ProcessBuilder.Redirect.appendTo(tty))
.redirectError(ProcessBuilder.Redirect.appendTo(tty))
.start();
但是,看起来您的bash脚本已经在处理重定向,因此不确定您是否需要在Java中执行此操作.
有关详细信息,请参阅this answer.