在 Java 中,PrintStream 是常用的輸出流之一。它適合把文字資料寫入檔案或控制台,也很適合用來記錄日誌。
FileOutputStream 以 byte 為單位寫入,若直接寫入整數 97,檔案內容會是 ASCII 的 a。若希望寫入文字 97,就要先轉成 byte 陣列。
PrintStream 更方便,因為它會把各種資料型別轉成文字。例如:
PrintStream ps = new PrintStream(file);
ps.println(97);
ps.println("hello");
ps.println(true);不論整數、字串、布林甚至物件,PrintStream 都會轉成可讀文字。
System.out 本身就是 PrintStream。透過 System.setOut,可以把原本印到控制台的內容導向檔案:
PrintStream ps = new PrintStream(file);
System.setOut(ps);
System.out.println("written to file");例外物件可透過 printStackTrace 輸出堆疊資訊。若傳入 PrintStream,就能把錯誤日誌寫入檔案:
try {
int n = 5 / 0;
} catch (Exception e) {
e.printStackTrace(ps);
}若希望每次執行都追加日誌,而不是覆寫檔案,可以使用 FileOutputStream 的追加模式:
PrintStream ps = new PrintStream(new FileOutputStream(file, true), true);
這樣 PrintStream 就會把新日誌接在舊內容後面。日誌記錄的目的不是只留一筆,而是持續追蹤程式行為,因此追加模式通常是必要設計。