java shell for executing/coordinating processes?

前端 未结 4 579
萌比男神i
萌比男神i 2021-01-14 06:20

I know about using Runtime.exec, you pass it a native program to run + arguments. If it\'s a regular program, you can run it directly. If it\'s a shell script, you have to r

4条回答
  •  滥情空心
    2021-01-14 06:37

    Ok, I've worked it out:

    Basically, you need to invoke bash with a "-s" and then write the full command string to it.

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

    Then use it like this:

    ShellExecutor excutor = new ShellExecutor("/bin/bash", "-s");
    try {
      System.out.println(excutor.execute("ls / | sort -r"));
    } catch (IOException e) {
      e.printStackTrace();
    }
    

    Obviously, you aught to do something with the error string but this is a working example.

提交回复
热议问题