java执行cmd命令的两种方法

一般java在执行CMD命令时,通常是使用Runtime.getRuntime.exec(command)来执行的,这个方法有两种细节要注意:

1.一般执行方法,代码如下,这种方法有时执行exe时会卡在那里。

 1 //一般的执行方法,有时执行exe会卡在那    stmt要执行的命令
 2     public static void executive(String stmt) throws IOException, InterruptedException {
 3         Runtime runtime = Runtime.getRuntime();  //获取Runtime实例
 4         //执行命令
 5         try {
 6             String[] command = {"cmd", "/c", stmt};
 7             Process process = runtime.exec(command);
 8             // 标准输入流(必须写在 waitFor 之前)
 9             String inStr = consumeInputStream(process.getInputStream());
10             // 标准错误流(必须写在 waitFor 之前)
11             String errStr = consumeInputStream(process.getErrorStream()); //若有错误信息则输出
14 int proc = process.waitFor(); 16 if (proc == 0) { 17 System.out.println("执行成功"); 18 } else { 19 System.out.println("执行失败" + errStr); 20 } 21 } catch (IOException | InterruptedException e) { 22 e.printStackTrace(); 23 } 24 } 25 26   /** 27 * 消费inputstream,并返回 28 */ 29 public static String consumeInputStream(InputStream is) throws IOException { 30 BufferedReader br = new BufferedReader(new InputStreamReader(is,"GBK")); 31 String s; 32 StringBuilder sb = new StringBuilder(); 33 while ((s = br.readLine()) != null) { 34 System.out.println(s); 35 sb.append(s); 36 } 37 return sb.toString(); 38 }

2.第二种方法是先生成一个缓存文件,用来缓存执行过程中输出的信息,这样在执行命令的时候不会卡。代码如下:

 1   //这个方法比第一个好,执行时不会卡  stmt要执行的命令
 2     public static void aaa(String stam){
 3         BufferedReader br = null;
 4         try {
 5             File file = new File("D:\daemonTmp");
 6             File tmpFile = new File("D:\daemonTmp\temp.tmp");//新建一个用来存储结果的缓存文件
 7             if (!file.exists()){
 8                 file.mkdirs();
 9             }
10             if(!tmpFile.exists()) {
11                 tmpFile.createNewFile();
12             }
13             ProcessBuilder pb = new ProcessBuilder().command("cmd.exe", "/c", stam).inheritIO();
14             pb.redirectErrorStream(true);//这里是把控制台中的红字变成了黑字,用通常的方法其实获取不到,控制台的结果是pb.start()方法内部输出的。
15             pb.redirectOutput(tmpFile);//把执行结果输出。
16             pb.start().waitFor();//等待语句执行完成,否则可能会读不到结果。
17             InputStream in = new FileInputStream(tmpFile);
18             br= new BufferedReader(new InputStreamReader(in));
19             String line = null;
20             while((line = br.readLine()) != null) {
21                 System.out.println(line);
22             }
23             br.close();
24             br = null;
25             tmpFile.delete();//卸磨杀驴。
26             System.out.println("执行完成");
27         } catch (Exception e) {
28             e.printStackTrace();
29         } finally {
30             if(br != null) {
31                 try {
32                     br.close();
33                 } catch (IOException e) {
34                     e.printStackTrace();
35                 }
36             }
37         }
38     }
 
原文地址:https://www.cnblogs.com/zhangzhiyong-/p/13364870.html