串流的来源或目的地不一定是档案,也可以是内存中的一个空间,例如一个位数组, 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。