J2SE 5.0 引入的 ProcessBuilder 取代了 Runtime.exec(),提供更靈活的外部程序啟動控制:環境變數設定、工作目錄指定、輸入輸出流重導向等。
import java.io.*;
import java.util.*;
public class NetworkInfoUtil {
public static List getPhysicalAddresses() {
List addresses = new ArrayList<>();
Process process;
try {
// 啟動 ipconfig /all
process = new ProcessBuilder("ipconfig", "/all").start();
} catch (IOException e) {
return addresses;
}
// 讀取輸出
StringBuilder output = new StringBuilder();
try (InputStream is = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
} catch (IOException e) {
return addresses;
}
// 解析 Physical Address
String content = output.toString();
int idx = content.indexOf("Physical Address");
while (idx >= 0) {
int start = content.indexOf(":", idx) + 1;
int end = start + 17; // MAC 格式 XX-XX-XX-XX-XX-XX
if (start > 0 && end <= content.length()) {
String mac = content.substring(start, end).trim();
if (mac.matches("([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}")) {
addresses.add(mac);
}
}
idx = content.indexOf("Physical Address", idx + 1);
}
return addresses;
}
public static void main(String[] args) {
getPhysicalAddresses().forEach(mac ->
System.out.printf("實體網卡位址: %s%n", mac));
}
}
environment() 可修改子程序環境變數;redirectErrorStream(true) 合併錯誤輸出BufferedReader 按行讀取,避免固定緩衝區截斷ifconfig 或 ip link,需根據 OS 動態選擇指令此模式可應用於:
wmic bios get serialnumber)wmic diskdrive get model,size)wmic product get name,version)StandardCharsets.UTF_8 或系統預設編碼