• Runtime.getRuntime().exec 类 防止阻塞



    import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.ArrayList; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.apache.log4j.Logger; import org.richinfo.gather.driver.MainEntry; //用两个线程来分别获取标准输出流和错误输出流,否则会造成io阻塞导致程序卡死 public class ShellExec { public static String execute(String cmd) throws IOException, InterruptedException { StringBuffer sb = new StringBuffer(); final Process p = Runtime.getRuntime().exec(cmd); /*为"错误输出流"单独开一个线程读取之,否则会造成标准输出流的阻塞*/ Thread t=new Thread(new InputStreamRunnable(p.getErrorStream(),"ErrorStream")); t.start(); BufferedReader reader = null; InputStream output = p.getInputStream(); //InputStream error = p.getErrorStream(); String line = ""; reader = new BufferedReader(new InputStreamReader(output)); while ((line = reader.readLine())!= null) { sb.append(line + " "); } p.waitFor(); // if (0x00 == sb.length()) { // reader = new BufferedReader(new InputStreamReader(error)); // // while ((line = reader.readLine())!= null) { // sb.append(line + " "); // } // } reader.close(); p.destroy(); return sb.toString(); } } /**读取InputStream的线程*/ class InputStreamRunnable implements Runnable { BufferedReader bReader=null; String type=null; public InputStreamRunnable(InputStream is, String _type) { try { bReader=new BufferedReader(new InputStreamReader(new BufferedInputStream(is),"UTF-8")); type=_type; } catch(Exception ex) { } } public void run() { String line; int lineNum=0; try { while((line=bReader.readLine())!=null) { lineNum++; //Thread.sleep(200); } bReader.close(); } catch(Exception ex) { } } }

      

  • 相关阅读:
    Layabox记录坑
    爬虫 Beautifulsoup 常用笔记
    opencv +python 提取roi目标区域全部像素的值 得出上下限 均匀值
    opencv + python 读取像素点 BGRtoRGB 以及注意事项
    pyinstaller打包python+opencv 无法在别人电脑上正常运行 问题所在:opencv_ffmpeg341_64.dll
    python 绝对路径相对路径
    面向对象编程-OOP-一张图看懂类和实例的基本用法
    python3 _笨方法学Python_日记_DAY7
    儋州“炰米”:美味的特制粮食
    PHP学习步骤
  • 原文地址:https://www.cnblogs.com/hrx-star/p/6645759.html
Copyright © 2020-2023  润新知