java io系列02之 ByteArrayInputStream的简介,源码分析和示例(包括InputStream)

简介: 我们以ByteArrayInputStream,拉开对字节类型的“输入流”的学习序幕。本章,我们会先对ByteArrayInputStream进行介绍,然后深入了解一下它的源码,最后通过示例来掌握它的用法。

 


我们以ByteArrayInputStream,拉开对字节类型的“输入流”的学习序幕。
本章,我们会先对ByteArrayInputStream进行介绍,然后深入了解一下它的源码,最后通过示例来掌握它的用法。

 

转载请注明出处:http://www.cnblogs.com/skywang12345/p/io_02.html

 

ByteArrayInputStream 介绍

 

ByteArrayInputStream 是字节数组输入流。它继承于InputStream。
它包含一个内部缓冲区,该缓冲区包含从流中读取的字节;通俗点说,它的内部缓冲区就是一个字节数组,而ByteArrayInputStream本质就是通过字节数组来实现的。
我们都知道,InputStream通过read()向外提供接口,供它们来读取字节数据;而ByteArrayInputStream 的内部额外的定义了一个计数器,它被用来跟踪 read() 方法要读取的下一个字节。

 


InputStream 函数列表

 

复制代码
// 构造函数
InputStream()

             int     available()
             void close() void mark(int readlimit) boolean markSupported() int read(byte[] buffer) abstract int read() int read(byte[] buffer, int offset, int length) synchronized void reset() long skip(long byteCount)
复制代码

 

ByteArrayInputStream 函数列表

 

复制代码
// 构造函数
ByteArrayInputStream(byte[] buf)
ByteArrayInputStream(byte[] buf, int offset, int length) synchronized int available() void close() synchronized void mark(int readlimit) boolean markSupported() synchronized int read() synchronized int read(byte[] buffer, int offset, int length) synchronized void reset() synchronized long skip(long byteCount)
复制代码

 

InputStream和ByteArrayInputStream源码分析

 

InputStream是ByteArrayInputStream的父类,我们先看看InputStream的源码,然后再学ByteArrayInputStream的源码。

 

1. InputStream.java源码分析(基于jdk1.7.40)

 

复制代码
 1 package java.io;
 2 
 3 public abstract class InputStream implements Closeable {  4  5 // 能skip的大小  6  private static final int MAX_SKIP_BUFFER_SIZE = 2048;  7  8 // 从输入流中读取数据的下一个字节。  9  public abstract int read() throws IOException; 10 11 // 将数据从输入流读入 byte 数组。 12  public int read(byte b[]) throws IOException { 13 return read(b, 0, b.length); 14  } 15 16 // 将最多 len 个数据字节从此输入流读入 byte 数组。 17  public int read(byte b[], int off, int len) throws IOException { 18 if (b == null) { 19 throw new NullPointerException(); 20 } else if (off < 0 || len < 0 || len > b.length - off) { 21 throw new IndexOutOfBoundsException(); 22 } else if (len == 0) { 23 return 0; 24  } 25 26 int c = read(); 27 if (c == -1) { 28 return -1; 29  } 30 b[off] = (byte)c; 31 32 int i = 1; 33 try { 34 for (; i < len ; i++) { 35 c = read(); 36 if (c == -1) { 37 break; 38  } 39 b[off + i] = (byte)c; 40  } 41 } catch (IOException ee) { 42  } 43 return i; 44  } 45 46 // 跳过输入流中的n个字节 47  public long skip(long n) throws IOException { 48 49 long remaining = n; 50 int nr; 51 52 if (n <= 0) { 53 return 0; 54  } 55 56 int size = (int)Math.min(MAX_SKIP_BUFFER_SIZE, remaining); 57 byte[] skipBuffer = new byte[size]; 58 while (remaining > 0) { 59 nr = read(skipBuffer, 0, (int)Math.min(size, remaining)); 60 if (nr < 0) { 61 break; 62  } 63 remaining -= nr; 64  } 65 66 return n - remaining; 67  } 68 69 public int available() throws IOException { 70 return 0; 71 } 72 73 public void close() throws IOException {} 74 75 public synchronized void mark(int readlimit) {} 76 77 public synchronized void reset() throws IOException { 78 throw new IOException("mark/reset not supported"); 79 } 80 81 public boolean markSupported() { 82 return false; 83 } 84 }
复制代码

 

2. ByteArrayInputStream.java源码分析(基于jdk1.7.40)

 

复制代码
  1 package java.io;
  2 
  3 public class ByteArrayInputStream extends InputStream {  4  5 // 保存字节输入流数据的字节数组  6  protected byte buf[];  7  8 // 下一个会被读取的字节的索引  9  protected int pos;  10  11 // 标记的索引  12  protected int mark = 0;  13  14 // 字节流的长度  15  protected int count;  16  17 // 构造函数:创建一个内容为buf的字节流  18  public ByteArrayInputStream(byte buf[]) {  19 // 初始化“字节流对应的字节数组为buf”  20  this.buf = buf;  21 // 初始化“下一个要被读取的字节索引号为0”  22  this.pos = 0;  23 // 初始化“字节流的长度为buf的长度”  24  this.count = buf.length;  25  }  26  27 // 构造函数:创建一个内容为buf的字节流,并且是从offset开始读取数据,读取的长度为length  28  public ByteArrayInputStream(byte buf[], int offset, int length) {  29 // 初始化“字节流对应的字节数组为buf”  30  this.buf = buf;  31 // 初始化“下一个要被读取的字节索引号为offset”  32  this.pos = offset;  33 // 初始化“字节流的长度”  34  this.count = Math.min(offset + length, buf.length);  35 // 初始化“标记的字节流读取位置”  36  this.mark = offset;  37  }  38  39 // 读取下一个字节  40  public synchronized int read() {  41 return (pos < count) ? (buf[pos++] & 0xff) : -1;  42  }  43  44 // 将“字节流的数据写入到字节数组b中”  45 // off是“字节数组b的偏移地址”,表示从数组b的off开始写入数据  46 // len是“写入的字节长度”  47  public synchronized int read(byte b[], int off, int len) {  48 if (b == null) {  49 throw new NullPointerException();  50 } else if (off < 0 || len < 0 || len > b.length - off) {  51 throw new IndexOutOfBoundsException();  52  }  53  54 if (pos >= count) {  55 return -1;  56  }  57  58 int avail = count - pos;  59 if (len > avail) {  60 len = avail;  61  }  62 if (len <= 0) {  63 return 0;  64 } 65 System.arraycopy(buf, pos, b, off, len); 66 pos += len; 67 return len; 68 } 69 70 // 跳过“字节流”中的n个字节。 71 public synchronized long skip(long n) { 72 long k = count - pos; 73 if (n < k) { 74 k = n < 0 ? 0 : n; 75 } 76 77 pos += k; 78 return k; 79 } 80 81 // “能否读取字节流的下一个字节” 82 public synchronized int available() { 83 return count - pos; 84 } 85 86 // 是否支持“标签” 87 public boolean markSupported() { 88 return true; 89 } 90 91 // 保存当前位置。readAheadLimit在此处没有任何实际意义 92 public void mark(int readAheadLimit) { 93 mark = pos; 94 } 95 96 // 重置“字节流的读取索引”为“mark所标记的位置” 97 public synchronized void reset() { 98 pos = mark; 99 } 100 101 public void close() throws IOException { 102 } 103 }
复制代码

 

说明
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)所标记的位置开始读取。

 

示例代码

 

关于ByteArrayInputStream中API的详细用法,参考示例代码(ByteArrayInputStreamTest.java):

 

复制代码
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/** * ByteArrayInputStream 测试程序 * * @author skywang */ public class ByteArrayInputStreamTest { private static final int LEN = 5; // 对应英文字母“abcddefghijklmnopqrsttuvwxyz” 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 main(String[] args) { String tmp = new String(ArrayLetters); System.out.println("ArrayLetters="+tmp); tesByteArrayInputStream() ; } /** * ByteArrayInputStream的API测试函数 */ private static void tesByteArrayInputStream() { // 创建ByteArrayInputStream字节流,内容是ArrayLetters数组 ByteArrayInputStream bais = new ByteArrayInputStream(ArrayLetters); // 从字节流中读取5个字节 for (int i=0; i<LEN; i++) { // 若能继续读取下一个字节,则读取下一个字节 if (bais.available() >= 0) { // 读取“字节流的下一个字节” int tmp = bais.read(); System.out.printf("%d : 0x%s\n", i, Integer.toHexString(tmp)); } } // 若“该字节流”不支持标记功能,则直接退出 if (!bais.markSupported()) { System.out.println("make not supported!"); return ; } // 标记“字节流中下一个被读取的位置”。即--标记“0x66”,因为因为前面已经读取了5个字节,所以下一个被读取的位置是第6个字节” // (01), ByteArrayInputStream类的mark(0)函数中的“参数0”是没有实际意义的。 // (02), mark()与reset()是配套的,reset()会将“字节流中下一个被读取的位置”重置为“mark()中所保存的位置” bais.mark(0); // 跳过5个字节。跳过5个字节后,字节流中下一个被读取的值应该是“0x6B”。 bais.skip(5); // 从字节流中读取5个数据。即读取“0x6B, 0x6C, 0x6D, 0x6E, 0x6F” byte[] buf = new byte[LEN]; bais.read(buf, 0, LEN); // 将buf转换为String字符串。“0x6B, 0x6C, 0x6D, 0x6E, 0x6F”对应字符是“klmno” String str1 = new String(buf); System.out.printf("str1=%s\n", str1); // 重置“字节流”:即,将“字节流中下一个被读取的位置”重置到“mark()所标记的位置”,即0x66。  bais.reset(); // 从“重置后的字节流”中读取5个字节到buf中。即读取“0x66, 0x67, 0x68, 0x69, 0x6A” bais.read(buf, 0, LEN); // 将buf转换为String字符串。“0x66, 0x67, 0x68, 0x69, 0x6A”对应字符是“fghij” String str2 = new String(buf); System.out.printf("str2=%s\n", str2); } }
复制代码

 

运行结果
ArrayLetters=abcdefghijklmnopqrstuvwxyz
0 : 0x61
1 : 0x62
2 : 0x63
3 : 0x64
4 : 0x65
str1=klmno
str2=fghij
结果说明
(01) ArrayLetters 是字节数组。0x61对应的ASCII码值是a,0x62对应的ASCII码值是b,依次类推...
(02) ByteArrayInputStream bais = new ByteArrayInputStream(ArrayLetters); 这句话是创建“字节流bais”,它的内容就是ArrayLetters。
(03) for (int i=0; i<LEN; i++) ; 这个for循环的作用就是从字节流中读取5个字节。每次调用bais.read()就从字节流中读取一个字节。
(04) bais.mark(0); 这句话就是“设置字节流的标记”,此时标记的位置对应的值是0x66。
(05) bais.skip(5); 这句话是跳过5个字节。跳过5个字节后,对应的字节流中下一个被读取的字节的值是0x6B。
(06) bais.read(buf, 0, LEN); 这句话是“从字节流中读取LEN个数据写入到buf中,0表示从buf的第0个位置开始写入”。
(07) bais.reset(); 这句话是将“字节流中下一个被读取的位置”重置到“mark()所标记的位置”,即0x66。

 

学完了ByteArrayInputStream输入流。下面,我们学习与之对应的输出流ByteArrayOutputStream。

 

相关文章
|
11月前
|
Java 开发工具
【Azure Storage Account】Java Code访问Storage Account File Share的上传和下载代码示例
本文介绍如何使用Java通过azure-storage-file-share SDK实现Azure文件共享的上传下载。包含依赖引入、客户端创建及完整示例代码,助你快速集成Azure File Share功能。
695 6
|
11月前
|
Java Unix Go
【Java】(8)Stream流、文件File相关操作,IO的含义与运用
Java 为 I/O 提供了强大的而灵活的支持,使其更广泛地应用到文件传输和网络编程中。!但本节讲述最基本的和流与 I/O 相关的功能。我们将通过一个个例子来学习这些功能。
398 1
|
12月前
|
IDE Java 关系型数据库
Java 初学者学习路线(含代码示例)
本教程为Java初学者设计,涵盖基础语法、面向对象、集合、异常处理、文件操作、多线程、JDBC、Servlet及MyBatis等内容,每阶段配核心代码示例,强调动手实践,助你循序渐进掌握Java编程。
1375 3
|
12月前
|
Java
java入门代码示例
本文介绍Java入门基础,包含Hello World、变量类型、条件判断、循环及方法定义等核心语法示例,帮助初学者快速掌握Java编程基本结构与逻辑。
787 0
Java API 开发者
440 0
|
Java 测试技术 API
Java IO流(二):文件操作与NIO入门
本文详解Java NIO与传统IO的区别与优势,涵盖Path、Files类、Channel、Buffer、Selector等核心概念,深入讲解文件操作、目录遍历、NIO实战及性能优化技巧,适合处理大文件与高并发场景,助力高效IO编程与面试准备。
|
SQL Java 数据库连接
Java IO流(一):字节流与字符流基础
本文全面解析Java IO流,涵盖字节流、字符流及其使用场景,帮助开发者理解IO流分类与用途,掌握文件读写、编码转换、异常处理等核心技术,通过实战案例提升IO编程能力。
|
存储 Java Linux
操作系统层面视角下 Java IO 的演进路径及核心技术变革解析
本文从操作系统层面深入解析Java IO的演进历程,涵盖BIO、NIO、多路复用器及Netty等核心技术。分析各阶段IO模型的原理、优缺点及系统调用机制,探讨Java如何通过底层优化提升并发性能与数据处理效率,全面呈现IO技术的变革路径与发展趋势。
297 3
|
监控 Java API
现代 Java IO 高性能实践从原理到落地的高效实现路径与实战指南
本文深入解析现代Java高性能IO实践,涵盖异步非阻塞IO、操作系统优化、大文件处理、响应式网络编程与数据库访问,结合Netty、Reactor等技术落地高并发应用,助力构建高效可扩展的IO系统。
406 0