Using Java to execute the bat command, if the bat operation is too long, it may cause a blocking problem and will not execute the bat until the server is shut down.
Such as:
Copy Code code as follows:
Runtime R=runtime.getruntime ();
Process P=null;
try{
String Path = "D:/test.bat";
p = r.exec ("cmd.exe/c" +path);
P.waitfor ();
}catch (Exception e) {
SYSTEM.OUT.PRINTLN ("Run Error:" +e.getmessage ());
E.printstacktrace ();
}
General Java exec is not to help you handle the problem of thread blocking, you need to manually handle.
After processing:
Copy Code code as follows:
Runtime R=runtime.getruntime ();
Process P=null;
try{
String Path = "D:/test.bat";
p = r.exec ("cmd.exe/c" +path);
Streamgobbler Errorgobbler = new Streamgobbler (P.geterrorstream (), "ERROR");
Errorgobbler.start ();
Streamgobbler Outgobbler = new Streamgobbler (P.getinputstream (), "STDOUT");
Outgobbler.start ();
P.waitfor ();
}catch (Exception e) {
SYSTEM.OUT.PRINTLN ("Run Error:" +e.getmessage ());
E.printstacktrace ();
}
The Streamgobbler classes are as follows:
Copy Code code as follows:
Package com.test.tool;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.OutputStream;
Import Java.io.PrintWriter;
/**
* for processing runtime.getruntime (). exec generated error stream and output stream
*/
public class Streamgobbler extends Thread {
InputStream is;
String type;
OutputStream OS;
Streamgobbler (InputStream is, String type) {
This (is, type, null);
}
Streamgobbler (InputStream is, String type, outputstream redirect) {
This.is = is;
This.type = type;
This.os = REDIRECT;
}
public void Run () {
InputStreamReader ISR = null;
BufferedReader br = null;
PrintWriter pw = null;
try {
if (OS!= null)
PW = new PrintWriter (OS);
ISR = new InputStreamReader (IS);
br = new BufferedReader (ISR);
String Line=null;
while (line = Br.readline ())!= null) {
if (PW!= null)
Pw.println (line);
System.out.println (type + ">" + line);
}
if (PW!= null)
Pw.flush ();
catch (IOException IoE) {
Ioe.printstacktrace ();
} finally{
try {
Pw.close ();
Br.close ();
Isr.close ();
catch (IOException e) {
E.printstacktrace ();
}
}
}
}
Run the bat and it won't block.