One of the causes of a block in the execution of an external program by a Java process

  • 2020-04-01 03:12:41
  • OfStack

Looked up a lot of information, almost began to turn over the Java source code, finally combined with an article (forget the source), thought of the output stream will block the process. Java process execution has one input stream and two output streams (relative to external programs). The process is blocked when two output streams have content output and the Java executor does not clear the output stream in time.
Now I post the code, hoping to help the peer in need:


 private static File toSwf(String sourceFile, String destFile, String command) {
  long beginTime = System.nanoTime();
  Runtime rt = Runtime.getRuntime();
  try {
   Process process = rt.exec(command);

   final InputStream isNormal = process.getInputStream();
   new Thread(new Runnable() {
       public void run() {
           BufferedReader br = new BufferedReader(new InputStreamReader(isNormal)); 
           StringBuilder buf = new StringBuilder();
     String line = null;
     try {
      while((line = br.readLine()) != null){
       buf.append(line + "n");
      }
     } catch (IOException e) {
      e.printStackTrace();
     }
     System.out.println(" The output result is: " + buf);
       }
   }).start(); //Start a separate thread to clear the buffer of process.getinputstream ()

   InputStream isError = process.getErrorStream();
   BufferedReader br2 = new BufferedReader(new InputStreamReader(isError)); 
   StringBuilder buf = new StringBuilder();
   String line = null;
   while((line = br2.readLine()) != null){
    buf.append(line + "n");
   }
   System.out.println(" The error output result is: " + buf);

   try {
    process.waitFor();
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  } catch (IOException e) {
   e.printStackTrace();
  }
  long endTime = System.nanoTime();
  System.out.println(" turn swf Time consuming : " + (endTime - beginTime) / 1000000000 + "  seconds   " + sourceFile);
  return new File(destFile);
 }


Related articles: