一般java在執(zhí)行CMD命令時,通常是使用Runtime.getRuntime.exec(command)來執(zhí)行的,這個方法有兩種細節(jié)要注意:
1.一般執(zhí)行方法,代碼如下,這種方法有時執(zhí)行exe時會卡在那里。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
//一般的執(zhí)行方法,有時執(zhí)行exe會卡在那 stmt要執(zhí)行的命令 public static void executive(String stmt) throws IOException, InterruptedException { Runtime runtime = Runtime.getRuntime(); //獲取Runtime實例 //執(zhí)行命令 try { Process process = runtime.exec(command); // 標(biāo)準(zhǔn)輸入流(必須寫在 waitFor 之前) String inStr = consumeInputStream(process.getInputStream()); // 標(biāo)準(zhǔn)錯誤流(必須寫在 waitFor 之前) String errStr = consumeInputStream(process.getErrorStream()); new ProcessClearStream(process.getInputStream(), "INFO" ).start(); new ProcessClearStream(process.getErrorStream(), "ERROR" ).start(); int proc = process.waitFor(); InputStream errorStream = process.getErrorStream(); //若有錯誤信息則輸出 if (proc == 0 ) { System.out.println( "執(zhí)行成功" ); } else { System.out.println( "執(zhí)行失敗" + errStr); } } catch (IOException | InterruptedException e) { e.printStackTrace(); } } /** * 消費inputstream,并返回 */ public static String consumeInputStream(InputStream is) throws IOException { BufferedReader br = new BufferedReader( new InputStreamReader(is, "GBK" )); String s; StringBuilder sb = new StringBuilder(); while ((s = br.readLine()) != null ) { System.out.println(s); sb.append(s); } return sb.toString(); } |
2.第二種方法是先生成一個緩存文件,用來緩存執(zhí)行過程中輸出的信息,這樣在執(zhí)行命令的時候不會卡。代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
//這個方法比第一個好,執(zhí)行時不會卡 stmt要執(zhí)行的命令 public static void aaa(String stam){ BufferedReader br = null ; try { File file = new File( "D:\\daemonTmp" ); File tmpFile = new File( "D:\\daemonTmp\\temp.tmp" ); //新建一個用來存儲結(jié)果的緩存文件 if (!file.exists()){ file.mkdirs(); } if (!tmpFile.exists()) { tmpFile.createNewFile(); } ProcessBuilder pb = new ProcessBuilder().command( "cmd.exe" , "/c" , stam).inheritIO(); pb.redirectErrorStream( true ); //這里是把控制臺中的紅字變成了黑字,用通常的方法其實獲取不到,控制臺的結(jié)果是pb.start()方法內(nèi)部輸出的。 pb.redirectOutput(tmpFile); //把執(zhí)行結(jié)果輸出。 pb.start().waitFor(); //等待語句執(zhí)行完成,否則可能會讀不到結(jié)果。 InputStream in = new FileInputStream(tmpFile); br= new BufferedReader( new InputStreamReader(in)); String line = null ; while ((line = br.readLine()) != null ) { System.out.println(line); } br.close(); br = null ; tmpFile.delete(); //卸磨殺驢。 System.out.println( "執(zhí)行完成" ); } catch (Exception e) { e.printStackTrace(); } finally { if (br != null ) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } } |
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.cnblogs.com/zhangzhiyong-/p/13364870.html