最近接觸到用java代碼呼叫主機的命令部分感覺有點意思整理總結一下
環境jdk1.8 作業系統win10,不用引入其他的包jdk自帶的api就可以
一、java呼叫ping命令
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
//呼叫本機ping命令
public class ExecPingDemo {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec("ping www.baidu.com");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream(), Charset.forName("GBK")));
String line;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
執行結果:
正在 Ping www.a.shifen.com [220.181.38.149] 具有 32 位元組的資料:
來自 220.181.38.149 的回復: 位元組=32 時間=55ms TTL=48
來自 220.181.38.149 的回復: 位元組=32 時間=55ms TTL=48
來自 220.181.38.149 的回復: 位元組=32 時間=55ms TTL=48
來自 220.181.38.149 的回復: 位元組=32 時間=54ms TTL=48
二、java呼叫打開本機的檔案
import java.io.IOException;
//打開檔案
public class ExecDemoOpen {
public static void main(String[] args) {
try {
String file = "D:/流程描述.txt"; // 檔案路徑
Process p = Runtime.getRuntime().exec("cmd /c start " + file); // 執行打開檔案的命令列
p.waitFor(); // 等待程式執行完畢
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
執行結果:就是指定的檔案打開了
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/549261.html
標籤:Java
