First, we need to increase the user's execution permissions for the script, that is,
The code copy is as follows:
String cmdstring = "chmod a+x test.sh";
Process proc = Runtime.getRuntime().exec(cmdstring);
proc.waitFor(); //Block until the above command is executed
cmdstring = "bash test.sh"; //It can also be ksh, etc.
proc = Runtime.getRuntime().exec(cmdstring);
// Pay attention to the following operations
string ls_1;
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(proc.getInputStream());
while ( (ls_1=bufferedReader.readLine()) != null);
bufferedReader.close();
proc.waitFor();
Why do you need the above operation?
The reason is: the output of the executable program may be relatively large, while the output buffer of the run window is limited, which will cause waitFor to be blocked all the time. The solution is to use the getInputStream and getErrorStream methods provided by the Process class provided by Java to allow the Java virtual machine to intercept the standard output and error output of the called program, and read the contents in the output buffer before the waitfor() command.
I hope you can like this article. Please leave me a message if you have any questions.