Java calls methods of Linux shell scripts

  • 2020-04-01 03:43:06
  • OfStack

First, we need to increase the user's permission to execute the script, i.e


 String cmdstring = "chmod a+x test.sh";
 Process proc = Runtime.getRuntime().exec(cmdstring);
 proc.waitFor(); //Block until the above command completes
 cmdstring = "bash test.sh"; //It could also be KSH and so on
 proc = Runtime.getRuntime().exec(cmdstring);
 //Notice the following
operation  string ls_1;
 BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(proc.getInputStream());
 while ( (ls_1=bufferedReader.readLine()) != null);
 bufferedReader.close();
 proc.waitFor();

Why do we have the above operation?

The reason: the executable may have too much output, and the output buffer of the running window is limited, causing waitFor to remain blocked. The solution is, the use of Java provides the Process of class provides getInputStream, getErrorStream methods of intercepting and capturing the caller to Java virtual machine (standard output and error output, in waitfor before () command to read out the contents of the output buffer.

I hope you enjoy this article. If you have any questions, please leave me a message.


Related articles: