首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> J2SE

J2SE 5.0 ProcessBuilder 實戰:Windows 環境下獲取網卡 MAC 位址

     編輯:J2SE

ProcessBuilder 簡介

J2SE 5.0 引入的 ProcessBuilder 取代了 Runtime.exec(),提供更靈活的外部程序啟動控制:環境變數設定、工作目錄指定、輸入輸出流重導向等。

實作範例:解析 ipconfig /all 獲取實體位址

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));
    }
}

關鍵技術點解析

  • ProcessBuilder 優勢:參數以 List 傳遞避免空白字元解析問題;environment() 可修改子程序環境變數;redirectErrorStream(true) 合併錯誤輸出
  • 輸出流處理:使用 BufferedReader 按行讀取,避免固定緩衝區截斷
  • 正則驗證:確保擷取內容符合 MAC 位址格式,過濾無效資料
  • 跨平台考量:Linux/macOS 可用 ifconfig 或 ip link,需根據 OS 動態選擇指令

擴展應用

此模式可應用於:

  • 獲取系統序號(wmic bios get serialnumber)
  • 磁碟資訊(wmic diskdrive get model,size)
  • 已安裝軟體列表(wmic product get name,version)

注意事項

  • 需適當處理權限問題(部分指令需管理員權限)
  • 輸出編碼可能因系統預設編碼不同而亂碼,建議指定 StandardCharsets.UTF_8 或系統預設編碼
  • 大量輸出時注意緩衝區滿導致子程序阻塞,需在獨立執行緒消費流
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved