Java调用外部程序

 
Java web开发调用外部 ffmpeg或mencoder转码...
遇到的问题是ffmpeg或mencoder进程阻塞, 需要停掉tomcat--javaw.exe进程之后才能执行ffmpeg.exe或mencoder.exe
 
问题的原因getErrorStream 和 getInputStream 缓冲区没有清空
 
解决的方法: 同时清空getErrorStream 和 getInputStream  的缓冲区
 
代码如下:
      ProcessBuilder builder = new ProcessBuilder();
      builder.command(commend);
      Process process = builder.start();
       final InputStream is1 = process.getInputStream();
       new Thread( new Runnable() {
             public void run() {
                     BufferedReader br = new BufferedReader( new InputStreamReader(is1));    
             try {
               while(br.readLine() != null) ;
            } catch (IOException e) {
              e.printStackTrace();
            }
             }
      }).start(); // 启动单独的线程来清空process.getInputStream()的缓冲区
      InputStream is2 = process.getErrorStream();
      BufferedReader br2 = new BufferedReader( new InputStreamReader(is2));    
      StringBuilder buf = new StringBuilder(); // 保存输出结果流
      String line = null;
       while((line = br2.readLine()) != null) buf.append(line);

本文出自 “wIsper 把技术做成艺术” 博客,转载请与作者联系!

你可能感兴趣的:(职场,休闲)