← 從零開始學 Java
第 62 課,共 88 課 · 10 XP
FileOutputStream
理論與題目說明
機器翻譯,尚未經母語人士審閱。
FileOutputStream 寫入位元組:
try (FileOutputStream out = new FileOutputStream("data.bin")) { // 覆寫
out.write(65); // 1 個位元組:'A'
out.write(new byte[]{1, 2, 3});
out.write("Hello".getBytes(StandardCharsets.UTF_8));
}
new FileOutputStream("data.bin", true) // 加到結尾
write(int) 寫入數字的最低位元組:write(300) 寫入的是 300 & 0xFF = 44。
位元組串流是給二進位格式用的:圖片、遊戲存檔、網路協定。處理文字時,
Writer 比較方便——它會自己把字元變成位元組。
題目。 輸入是整數。把每一個以1 個位元組寫進 out.bin(write(n)),接著以 UTF-8 寫入字串
END。輸出檔案的大小(new File(...).length()),再重新讀取檔案
(Files.readAllBytes),用空白分隔、以無號數輸出它的位元組(b & 0xFF)。