How to code in java to run unix shell script which

2019-09-06 10:48发布

问题:

I am using cygwin to get unix environment on windows.

I have some shell script that run on cygwin to perform syncing works and other things. I want to executes these script through java code.

Also during executing of scripts on cygwin , certain information is displayed on terminal by using simple echo command.. I want to show all that information in my application.

How can I do this??

回答1:

Use the Runtime class to run Cygwin. This is very brittle, and dependent upon your setup, but on my machine I would do:

Runtime r = Runtime.getRuntime();
Process p = r.exec("C:\\dev\\cygwin\\bin\\mintty.exe --exec /cygpath/to/foo.sh");

Then wait for the Process to complete, and get a handle to it's InputStream objects to see what was sent to stdout and stderror.

The first part of the command is to run cygwin, and the second is to execute some script, or command (using -e or --exec). I would test this command on the DOS prompt to see if it works first before cutting any code. Also, take a look at the options available by doing:

C:\dev\cygwin\bin\mintty.exe --help

Also from within the DOS prompt.

EDIT: The following works for me to print version information


public class RuntimeFun {
   public static void main(String[] args) throws Exception {
      Runtime r = Runtime.getRuntime();
      Process p = r.exec("C:\\dev\\cygwin\\bin\\mintty.exe --version");
      p.waitFor();

      BufferedReader buf = new BufferedReader(
               new InputStreamReader(
                        p.getInputStream()));
      String line = buf.readLine();
      while (line != null) {
          System.out.println(line);
          line = buf.readLine();
      }
   }
}

Unfortunately, can't seem to get it working with --exec, so you're going to have to do some more research there.



回答2:

You can use something like this

String cmd = "ls -al";
Runtime run = Runtime.getRuntime();
Process pr = run.exec(cmd);
pr.waitFor();
BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while ((line=buf.readLine())!=null) {
    System.out.println(line);
}

p.s. this doesn't handle errors