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

779 篇文章 0 订阅
<script type="text/javascript"> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
<script type="text/javascript"> </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"> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
<script type="text/javascript"> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
好的,下面是一个使用ProcessBuilder调用Linux命令并处理输出和报错信息的Java方法: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; public class LinuxCommandExecutor { public static String executeCommand(List<String> command, int timeoutInSeconds) throws Exception { ProcessBuilder processBuilder = new ProcessBuilder(command); Process process = processBuilder.start(); StringBuilder output = new StringBuilder(); StringBuilder error = new StringBuilder(); BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(process.getInputStream())); BufferedReader stderrReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); long startTime = System.currentTimeMillis(); while (isAlive(process)) { readStream(stdoutReader, output); readStream(stderrReader, error); if (System.currentTimeMillis() - startTime >= timeoutInSeconds * 1000) { process.destroy(); throw new Exception("Command timed out after " + timeoutInSeconds + " seconds"); } } readStream(stdoutReader, output); readStream(stderrReader, error); int exitCode = process.waitFor(); if (exitCode != 0) { throw new Exception("Command exited with non-zero exit code: " + exitCode + "\nError: " + error.toString()); } return output.toString(); } private static void readStream(BufferedReader reader, StringBuilder output) throws IOException { String line; while ((line = reader.readLine()) != null) { output.append(line).append("\n"); } } private static boolean isAlive(Process process) { try { process.exitValue(); return false; } catch (IllegalThreadStateException e) { return true; } } } ``` 这个方法接收一个命令列表和一个超时时间(以秒为单位),执行该命令,并返回输出结果。如果命令返回非零退出码,则会抛出异常。如果命令在超时时间内没有完成,则会抛出超时异常。 使用示例: ```java List<String> command = List.of("ls", "-l"); String output = LinuxCommandExecutor.executeCommand(command, 10); System.out.println(output); ``` 这个例子执行ls -l命令,并将结果输出到控制台。如果命令执行时间超过10秒,则会抛出超时异常。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值