Java 提供豐富的輸入輸出流,其中管道流是一種特殊機制,用於不同執行緒間直接傳遞資料。一個執行緒寫入輸出管道,另一個執行緒從輸入管道讀取,無需臨時檔案等中介媒介。本文將介紹管道基本概念,並以 pipeapp 實例詳細說明。
Java 提供兩個專門類別處理管道:
PipedInputStream:管道輸出端,執行緒從管道讀取資料PipedOutputStream:管道輸入端,執行緒向管道寫入資料建立管道流步驟:
PipedOutputStream pipeOut = new PipedOutputStream();
PipedInputStream pipeIn = new PipedInputStream(pipeOut);
建立後即可像操作檔案一樣進行資料讀寫。
程式由三個執行緒組成:主執行緒 pipeapp.java 及其啟動的兩個次級執行緒 ythread.java、zthread.java。流程如下:
input.txt(每行為 "x")讀取資料ythread 將 "x" 轉換為 "y"zthread 將 "y" 轉換為 "z"// 建立檔案輸入流
FileInputStream xFileIn = new FileInputStream("input.txt");
// 啟動 ythread,取得其輸出管道(作為下一階段輸入)
InputStream yInPipe = pipeApp.changeToY(xFileIn);
// 啟動 zthread,取得最終輸入管道
InputStream zInPipe = pipeApp.changeToZ(yInPipe);
// 讀取並顯示結果
DataInputStream inputStream = new DataInputStream(zInPipe);
String str;
while ((str = inputStream.readLine()) != null) {
System.out.println(str);
}
inputStream.close();
// 定位輸入流
DataInputStream xFileIn = new DataInputStream(inputStream);
// 建立管道
PipedOutputStream pipeOut = new PipedOutputStream();
PipedInputStream pipeIn = new PipedInputStream(pipeOut);
// 將輸出管道包裝為 PrintStream 方便寫入
PrintStream printStream = new PrintStream(pipeOut);
// 建立並啟動 ythread
YThread yThread = new YThread(xFileIn, printStream);
yThread.start();
return pipeIn; // 返回輸入管道供下一階段使用
邏輯與 changeToY() 類似,接收上一階段輸入管道,建立新管道,啟動 ZThread 將 "y" 轉為 "z",返回最終輸入管道。
PipedInputStream 與 PipedOutputStream 必須配對使用