ByteArrayOutputStream :http://www.javashuo.com/article/p-pwcrmiuk-dh.htmlhtml
ByteArrayInputStream 是字节数组输入流。它继承于InputStream。
它包含一个内部缓冲区,该缓冲区包含从流中读取的字节;通俗点说,它的内部缓冲区就是一个字节数组,而ByteArrayInputStream本质就是经过字节数组来实现的。
咱们都知道,InputStream经过read()向外提供接口,供它们来读取字节数据;而ByteArrayInputStream 的内部额外的定义了一个计数器,它被用来跟踪 read() 方法要读取的下一个字节。数组
说明:
ByteArrayInputStream其实是经过“字节数组”去保存数据。
(01) 经过ByteArrayInputStream(byte buf[]) 或 ByteArrayInputStream(byte buf[], int offset, int length) ,咱们能够根据buf数组来建立字节流对象。
(02) read()的做用是从字节流中“读取下一个字节”。
(03) read(byte[] buffer, int offset, int length)的做用是从字节流读取字节数据,并写入到字节数组buffer中。offset是将字节写入到buffer的起始位置,length是写入的字节的长度。
(04) markSupported()是判断字节流是否支持“标记功能”。它一直返回true。
(05) mark(int readlimit)的做用是记录标记位置。记录标记位置以后,某一时刻调用reset()则将“字节流下一个被读取的位置”重置到“mark(int readlimit)所标记的位置”;也就是说,reset()以后再读取字节流时,是从mark(int readlimit)所标记的位置开始读取。spa
代码示例:code
private static final byte[] ArrayLetters = { 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A }; public static void test() throws IOException { ByteArrayInputStream bi = new ByteArrayInputStream(ArrayLetters); // 从字节流中读取5个字节 for (int i = 0; i < 5; i++) { // 若能读取下一个字节 if (bi.available() > 0) { int temp = bi.read(); System.out.println(Integer.toHexString(temp)); } } // 若此类不支持标记,则退出 if (!bi.markSupported()) { System.out.println("make not supported!"); } // 标记下一个被读取的位置,"0x66" bi.mark(0); // 跳过5个字节 bi.skip(5); // 读取5个字节 byte[] buff = new byte[5]; bi.read(buff); System.out.println(new String(buff)); // 重置 bi.reset(); bi.read(buff); System.out.println(new String(buff));