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 + "\n");
	    }
	    p.waitFor();
//	    if (0x00 == sb.length()) {
//	    	reader = new BufferedReader(new InputStreamReader(error));
//	    	
//	    	while ((line = reader.readLine())!= null) {
//	    		sb.append(line + "\n");
//		    }
//	    }
	    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)  
        {  
        }  
    }  
}  
相關文章
相關標籤/搜索