从Java同步运行shell脚本 [英] Run shell script from Java Synchronously

查看:193
本文介绍了从Java同步运行shell脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图执行从Java的Bash shell脚本,它使用这块code的运行正常。

I am trying to execute a Bash Shell script from Java and it runs fine using this piece of code.

public void executeScript() {
    try {
        new ProcessBuilder("myscript.sh").start();
        System.out.println("Script executed successfully");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

以上code运行正常异步。但我想实现的是同步执行code。我想Java进程要等到脚本执行完毕后再执行下一批code的。

The above code runs fine asynchronously. But what I would like to achieve is to execute the code synchronously. I would like the Java process to wait until the execution of the script is completed and then execute the next batch of code.

要总结,我想打印语句 - 成功执行脚本要执行 的批处理文件(myscript.sh)完成后,执行

To summarize, I would like the "Print statement - Script executed successfully" to be executed after the batch file ("myscript.sh") completes execution.

感谢

推荐答案

您想等待进程结束,也就是<一个href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Process.html#waitFor%28%29\">waitFor()像这样

You want to wait for the Process to finish, that is waitFor() like this

public void executeScript() {
  try {
    ProcessBuilder pb = new ProcessBuilder(
      "myscript.sh");
    Process p = pb.start();     // Start the process.
    p.waitFor();                // Wait for the process to finish.
    System.out.println("Script executed successfully");
  } catch (Exception e) {
    e.printStackTrace();
  }
}

这篇关于从Java同步运行shell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆