文章詳情頁
使用ProcessBuilder調用外部命令,并返回大量結果
瀏覽:65日期:2024-07-19 08:19:14
內容: 在網上常見的用Java調用外部命令返回結果的方法是: process =runtime.exec(cmd) is = process.getInputStream(); isr=new InputStreamReader(is); br =new BufferedReader(isr); while( (line = br.readLine()) != null ) { out.println(line); out.flush(); } 這種方法在遇到像cvs checkout modules這樣不能馬上返回結果的命令來說是無效的,不僅得不到返回結果,進程也會終止。其原因是,process在沒有來得及gegtInputStream是,調用了BufferedReader.readLine其返回結果是null,也就是說循環一開始就會停止。因此想要正常運行只能直接讀取process.getInputStream(),如下:import java.io.*;/** * * @author tyrone * */public class CMDExecute { /** * @param cmd * @return * @throws IOException */ public synchronized String run(String[] cmd,String workdirectory) throws IOException{ String line=null; String result=''; try { ProcessBuilder builder = new ProcessBuilder(cmd); //set working directory if (workdirectory!=null) builder.directory(new File(workdirectory)); builder.redirectErrorStream(true); Process process = builder.start(); InputStream in=process.getInputStream(); byte[] re=new byte[1024]; while (in.read(re)!= -1) { System.out.println(new String(re)); result = result + new String(re); } in.close(); } catch (Exception ex) { ex.printStackTrace(); } return result; } /** * @param args=cvs log */ public static void main(String[] args){ String result=null; CMDExecute cmdexe=new CMDExecute(); try { result= cmdexe.run(args,'D:MyProjectcolimasaxis_c'); System.out.println(result); }catch ( IOException ex ){ ex.printStackTrace(); } }}經過測試,本方法可以運行返回大量結果的應用程序。我的blog:http://blog.csdn.net/tyrone1979 Java, java, J2SE, j2se, J2EE, j2ee, J2ME, j2me, ejb, ejb3, JBOSS, jboss, spring, hibernate, jdo, struts, webwork, ajax, AJAX, mysql, MySQL, Oracle, Weblogic, Websphere, scjp, scjd 在網上常見的用Java調用外部命令返回結果的方法是: process =runtime
相關文章:
1. Vue 路由返回恢復頁面狀態的操作方法2. django 數據庫 get_or_create函數返回值是tuple的問題3. 前端獲取http狀態碼400的返回值實例4. 解決python 兩個時間戳相減出現結果錯誤的問題5. Android Fragment監聽返回鍵的一種合理方式6. Python 統計列表中重復元素的個數并返回其索引值的實現方法7. vue 路由緩存 路由嵌套 路由守衛 監聽物理返回操作8. 解決ASP中http狀態跳轉返回錯誤頁的問題9. 解決python cv2.imread 讀取中文路徑的圖片返回為None的問題10. 基于ajax后臺返回的數據為空前臺顯示出現undefined的解決方法
排行榜