在企業級郵件系統中,病毒掃描與垃圾郵件過濾常需調用外部專業引擎。郵件實質為包含特殊分隔符的檔案結構,附件嵌入其中。系統通過調用外部殺毒軟體掃描郵件檔案,根據返回碼判斷是否攜帶病毒;垃圾郵件判斷則採用評分機制,對比特徵庫計算得分,超過閾值即判定為垃圾郵件。核心邏輯在於:Java 負責流程編排與結果解析,實際檢測能力由外部專業工具提供。
package com.cmd;
import java.lang.*;
import java.io.*;
public class Process {
public static void main(String[] args) {
java.lang.Process process = null;
try {
// 執行系統命令,例如查詢用戶列表
process = Runtime.getRuntime().exec("net user");
ByteArrayOutputStream resultOutStream = new ByteArrayOutputStream();
InputStream errorInStream = new BufferedInputStream(process.getErrorStream());
InputStream processInStream = new BufferedInputStream(process.getInputStream());
int num = 0;
byte[] bs = new byte[1024];
// 讀取錯誤流
while ((num = errorInStream.read(bs)) != -1) {
resultOutStream.write(bs, 0, num);
}
// 讀取標準輸出流
while ((num = processInStream.read(bs)) != -1) {
resultOutStream.write(bs, 0, num);
}
String result = new String(resultOutStream.toByteArray());
System.out.println(result);
// 資源釋放
errorInStream.close();
processInStream.close();
resultOutStream.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (process != null) {
process.destroy();
}
}
}
}
getInputStream()(標準輸出)與 getErrorStream()(標準錯誤),避免緩衝區填滿導致進程阻塞。finally 區塊確保流關閉與進程銷毀,防止資源洩漏與殭屍進程。ProcessBuilder 替代 Runtime.exec(),提供更靈活的環境變數、工作目錄控制。process.waitFor()),而非單純依賴輸出文本。ProcessHandle API)。Java 調用外部程式是系統整合常用手段,掌握雙流處理、資源釋放與異常處理細節,能構建穩健的外部命令執行模組,廣泛應用於病毒掃描、圖像處理、文件轉換等場景。