Java程式執行cmd命令
阿新 • • 發佈:2018-11-28
一:編寫程式實現執行cmd指令.
1.1 思路分析:使用Process的exec()將cmd的執行結果通過java的IO流輸出到IDE的控制檯即可.
Process的exec()方法.看一下原始碼,發現有好幾個構造方法,傳單個cmd的,傳cmd陣列的等.
public Process exec(String command) throws IOException { return exec(command, null, null); }
public Process exec(String command, String[] envp) throws IOException {
return exec(command, envp, null);
}
1.2 這裡實現單個命令結果輸出.cmd的指令是ping www.baidu.com.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class DosUtil { public static void main(String[] args) { // Java呼叫 dos命令 String cmd = "ping www.baidu.com"; try { Process process = Runtime.getRuntime().exec(cmd); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String content = br.readLine(); while (content != null) { System.out.println(content); content = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } } }
執行結果:(出現亂碼)