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