使用ProcessBuilder调用外部命令,并返回大量结果

来源:互联网 发布:数据透视表怎么合计 编辑:程序博客网 时间:2024/06/14 22:10
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

  在网上常见的用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=cvslog */public static void main(String[] args){String result=null;CMDExecute cmdexe=new CMDExecute();try {result= cmdexe.run(args,"D://MyProject//colimas//axis_c");System.out.println(result);}catch ( IOException ex ){ex.printStackTrace();}}}经过测试,本方法可以运行返回大量结果的应用程序。

<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>