How to code in java to run unix shell script which use rSync internally in windows environment using cygwin?

微笑、不失礼 提交于 2019-12-13 07:16:08

问题


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



来源:https://stackoverflow.com/questions/9840970/how-to-code-in-java-to-run-unix-shell-script-which-use-rsync-internally-in-windo

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