串流的來源或目的地不一定是檔案,也可以是記憶體中的一個空間,例如一個位元陣列, ByteArrayInputStream、ByteArrayOutputStream即是將位元陣列當作串流輸入來源、輸出目的地的工具類別。
ByteArrayInputStream可以將一個陣列當作串流輸入的來源,而ByteArrayOutputStream則可以將一個位元陣列當作串流輸出的目的地,這兩個類別基本上比較少使用,在這邊舉一個簡單的檔案位元編輯程式作為例子。
您開啟一個簡單的文字檔案,當中有簡單的ABCDEFG等字元,在讀取檔案之後,您可以直接以程式來指定檔案的位元位置,以修改您所指定的字元,程式的作法是將檔案讀入陣列中,修改位置的指定被用作陣列的指針,在修改完陣列內容之後,您重新將陣列存回檔案,範例如下:
package onlyfun.caterpillar; import java.io.*; import java.util.*; public class ByteArrayStreamDemo { public static void main(String[] args) { try { File file = new File(args[0]); BufferedInputStream bufferedInputStream = new BufferedInputStream( new FileInputStream(file));
// 將檔案讀入位元陣列 ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream(); byte[] bytes = new byte[1]; while(bufferedInputStream.read(bytes) != -1) { arrayOutputStream.write(bytes); } arrayOutputStream.close(); bufferedInputStream.close();
// 顯示位元陣列內容 bytes = arrayOutputStream.toByteArray(); for(byte b : bytes) { System.out.print((char) b); } System.out.println();
// 讓使用者輸入位置與字元修改位元陣列內容 Scanner scanner = new Scanner(System.in); System.out.print("輸入修改位置:"); int pos = scanner.nextInt(); System.out.print("輸入修改字元:"); bytes[pos-1] = (byte) scanner.next().charAt(0);
// 將位元陣列內容存回檔案 ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); BufferedOutputStream bufOutputStream = new BufferedOutputStream( new FileOutputStream(file)); byte[] tmp = new byte[1]; while(byteArrayInputStream.read(tmp) != -1) bufOutputStream.write(tmp); byteArrayInputStream.close(); bufOutputStream.flush(); bufOutputStream.close(); } catch(ArrayIndexOutOfBoundsException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); } } }
執行結果:
java onlyfun.caterpillar.ByteArrayStreamDemo test.txt
ABCDEFG
輸入修改位置:2
輸入修改字元:K
|
再開啟test.txt,您會發現B已經被覆蓋為K。
|