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

J2SE 5.0 新特性:ProcessBuilder 靈活啟動外部程序

     編輯:Java 程式設計入門

JDK 5.0 引入 ProcessBuilder,取代笨重的 Runtime.exec(),提供更直觀的 API 控制外部程序啟動、環境變數、工作目錄、輸入輸出重導向。本文以 Windows 下讀取網卡 MAC 位址為例實戰演示。

為什麼選 ProcessBuilder?

  • 物件導向設計,參數以 List 傳遞,避免字串解析歧義
  • 支援 environment() 直接操作環境變數 Map
  • directory(File) 指定工作目錄
  • redirectInput/Output/Error 靈活重導向流
  • 啟動流程僅需 start() 一行

實戰範例:解析 ipconfig /all 取得實體網卡 MAC

package com.example.jdk5;

import java.io.*;
import java.util.*;

public class ProcessBuilderDemo {

    public static List<String> getPhysicalAddresses() {
        List<String> addresses = new ArrayList<>();
        Process process = null;

        try {
            // 啟動 ipconfig /all
            process = new ProcessBuilder("ipconfig", "/all").start();
        } catch (IOException e) {
            return addresses; // 空列表
        }

        // 讀取標準輸出
        StringBuilder output = new StringBuilder();
        try (InputStream in = process.getInputStream();
             BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }
        } catch (IOException e) {
            // 忽略讀取錯誤
        }

        // 解析輸出尋找 Physical Address
        String content = output.toString();
        String keyword = "Physical Address";
        int idx = content.indexOf(keyword);
        while (idx >= 0) {
            // 跳過關鍵字與分隔符,取後 17 字元 (XX-XX-XX-XX-XX-XX)
            int start = content.indexOf(":", idx) + 2;
            if (start > 1 && start + 17 <= content.length()) {
                addresses.add(content.substring(start, start + 17).trim());
            }
            idx = content.indexOf(keyword, idx + 1);
        }
        return addresses;
    }

    public static void main(String[] args) {
        List<String> macs = getPhysicalAddresses();
        for (String mac : macs) {
            System.out.printf("實體網卡 MAC: %s%n", mac);
        }
    }
}

關鍵點解析

  1. ProcessBuilder 建構式:接受可變參數或 List<String>,第一個為指令,其餘為參數,自動處理空白與引號。
  2. 流程啟動:start() 回傳 Process 物件,非阻塞。
  3. 輸出讀取:務必消耗標準輸出/錯誤流,否則緩衝區滿會導致子程序掛起。範例使用 BufferedReader 逐行讀取,比固定位元組陣列更穩健。
  4. 跨平台注意:Windows 用 ipconfig /all,Linux/Mac 用 ifconfig 或 ip link,關鍵字與輸出格式不同,實際專案需判斷 System.getProperty("os.name") 分流處理。

進階用法速查

需求API
設定環境變數pb.environment().put("VAR", "value")
指定工作目錄pb.directory(new File("/path"))
合併錯誤輸出到標準輸出pb.redirectErrorStream(true)
輸出導向檔案pb.redirectOutput(ProcessBuilder.Redirect.to(file))
等待結束並取得退出碼process.waitFor()

ProcessBuilder 讓 Java 與系統原生指令互動更優雅、安全,是系統管理、自動化腳本、整合舊系統的利器。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved