直接上範例程式碼,
其中 String command 的內容是要執行的指令,範例為 ping www.google.com,
並在最後把指令執行完後的結果輸出。
需要注意的地方是 Windows 和 Linux 的 String[] commands 有一些不同,
Windows 是:
cmd.exe /c "some command"
Linux 是:
/bin/sh -c "some command"
說明:
- 需要注意的地方是 Windows 和 Linux 的 String[] commands 有一些不同
- 在 jdk 1.5 (或以下版本),
,
參考資料:
package Main; import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static void main(String[] args) { String command = "ping www.google.com"; String[] commands = {"cmd.exe", "/c", command }; // windows command String SYSTEM_OS = System.getProperty("os.name"); if (SYSTEM_OS.toLowerCase().contains("windows")) { commands = new String[] {"cmd.exe", "/c", command }; } else if (SYSTEM_OS.toLowerCase().contains("linux")) { // windows command commands = new String[] {"/bin/sh", "-c", command }; // linux command } try { final Process p = Runtime.getRuntime().exec(commands); // read error BufferedReader errorBufferedReader = new BufferedReader(new InputStreamReader(p.getErrorStream())); StringBuffer errorStringBuffer = new StringBuffer(); String errorLine = ""; //In jdk 1.5, errorStream.readLine sometimes stock and never return, //if this happened, you can just close the errorStream directly (don't read the response) to let inputStream can read regular response. while ((errorLine = errorBufferedReader.readLine()) != null) { errorStringBuffer.append(errorLine + "\n"); } if (errorStringBuffer.length() > 0) { errorStringBuffer.deleteCharAt(errorStringBuffer.length() - 1); } errorBufferedReader.close(); // read regular output BufferedReader reqularOuputBufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream())); StringBuffer reqularOuputStringBuffer = new StringBuffer(); String reqularOuputString = ""; while ((reqularOuputString = reqularOuputBufferedReader.readLine()) != null) { reqularOuputStringBuffer.append(reqularOuputString + "\n"); } if (reqularOuputStringBuffer.length() > 0) { reqularOuputStringBuffer.deleteCharAt(reqularOuputStringBuffer.length() - 1); } reqularOuputBufferedReader.close(); int result = p.waitFor(); System.out.println("result: " + result); System.out.println("reqular output:\n" + reqularOuputStringBuffer.toString()); System.out.println("error output:\n" + errorStringBuffer.toString()); /* result: 0 reqular output: Ping www.google.com [2404:6800:4012:3::2004] (使用 32 位元組的資料): 回覆自 2404:6800:4012:3::2004: 時間=6ms 回覆自 2404:6800:4012:3::2004: 時間=6ms 回覆自 2404:6800:4012:3::2004: 時間=8ms 回覆自 2404:6800:4012:3::2004: 時間=7ms 2404:6800:4012:3::2004 的 Ping 統計資料: 封包: 已傳送 = 4,已收到 = 4, 已遺失 = 0 (0% 遺失), 大約的來回時間 (毫秒): 最小值 = 6ms,最大值 = 8ms,平均 = 6ms error output: */ } catch (Exception e) { e.printStackTrace(); } } }
沒有留言 :
張貼留言