Run shell script from Java Synchronously

不打扰是莪最后的温柔 提交于 2019-12-17 12:35:47

问题


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();
    }
}

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.

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

Thanks


回答1:


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();
  }
}



回答2:


The above code doesn't work if I wanted to move a file from one location to another, so I've fixed it with below code.

class Shell

{

  public static void main(String[] args) {
    try {
      ProcessBuilder pb = new ProcessBuilder("/home/sam/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();
      }

  }
}


myscript.sh
#!/bin/bash   
mv -f /home/sam/Download/cv.pdf /home/sam/Desktop/



回答3:


Use Process#waitFor() to pause the Java code until the script terminates. As in

    try {
        Process p = new ProcessBuilder("myscript.sh").start();
        int rc = p.waitFor();
        System.out.printf("Script executed with exit code %d\n", rc);


来源:https://stackoverflow.com/questions/20592397/run-shell-script-from-java-synchronously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!