Java IO 节点流 ByteArrayInput/OutputStream

@author ixenos

 

 

ByteArrayInputStream


包含一个内部缓冲区(字节数组byte[]),该缓冲区包含从流中读取的字节。

关闭 ByteArrayInputStream 无效。此类中的方法在关闭此流后仍可被调用,而不会产生任何 IOException。 

 

#Constructors

ByteArrayInputStream(byte[] buf) //使用创建者预设的buf作为其缓冲区数组,通常buf就是数据源
ByteArrayInputStream(byte[] buf, int offset, int lenght) //使用buf作为其缓冲区数组,参数offset指定从数组中开始读取数据的起始下标位置,lenght指定从数组中读取的字节数。 

 

int read(byte[] b, int off, int len) 
         从此字节输入流中给定偏移量处开始将各字节读取出来并写到指定的 byte 数组b中。

   返回:(本次)读取的字节数;如果已到达流末尾,则返回 -1

int  read()返回下一个字节,如果到达流末尾,则返回 -1

 

 

ByteArrayOutputStream


在内存中创建一个字节数组缓冲区,所有发送到输出流的数据保存在该字节数组缓冲区中。

缓冲区会随着数据的不断写入而自动增长。默认构造是32

可使用 toByteArray() 和 toString() 获取数据

关闭 ByteArrayOutputStream 无效。此类中的方法在关闭此流后仍可被调用,而不会产生任何 IOException

 

#字段protected int count  缓冲区中的有效字节数,即表示当前缓冲区中数据的字节数

#public void reset()  将此 byte 数组输出流的 count 字段重置为零,从而丢弃输出流中目前已累积的所有输出。通过重新使用已分配的缓冲区空间,可以再次使用该输出流。 

#Constructors

OutputStream bOut = new ByteArrayOutputStream(); //创建一个32字节(默认大小)的缓冲区,内部是this(32),即调用了另一个构造器
OutputStream bOut = new ByteArrayOutputStream(int a); //创建一个大小为a字节的缓冲区,即new byte[a]

#Methods

public byte[] toByteArray()
创建一个新分配的字节数组。数组的大小和当前输出流的大小,内容是当前输出流的拷贝。
public String toString()
将缓冲区的内容转换为字符串,根据平台的默认字符编码将字节转换成字符。
public void write(int w)
 将指定的字节写入此字节数组输出流。
public void write(byte []b, int of, int len)
 将指定字节数组中从偏移量 off 开始的 len 个字节写入此字节数组输出流。
public void writeTo(OutputStream outSt)
将此字节数组输出流的全部内容写入到指定的输出流参数中。

 

 

关于内部缓冲区


  二者同时使用时缓冲区是没有联系的,但二者原理一致,作为中间缓存

#ByteArrayInputStream 先提供一个缓冲区存放需要的数据,该数组相当于数据源,读取时,从该数组取出 sender----->buf------>you

 1     //通过输入流读取一个字节的数据,实际上是在缓冲区buf中读
 2     //buf - 可看作数据源
 3     public synchronized int read() {
 4     return (pos < count) ? (buf[pos++] & 0xff) : -1; 
 5     }
 6 
 7     //通过输入流读取缓冲区的数据,读入存储数组b中
 8     //b - 存储读入数据的缓冲区
 9     public synchronized int read(byte b[], int off, int len) {
10         if (b == null) {
11             throw new NullPointerException();
12         } else if (off < 0 || len < 0 || len > b.length - off) {
13             throw new IndexOutOfBoundsException();
14         }
15 
16         if (pos >= count) {
17             return -1;
18         }
19 
20         int avail = count - pos;
21         if (len > avail) {
22             len = avail;
23         }
24         if (len <= 0) {
25             return 0;
26         }
27         System.arraycopy(buf, pos, b, off, len); //因为是数组对数组,所以直接copy过去
28         pos += len;
29         return len;
30     }
View Code

相关文章:

  • 2022-01-14
  • 2021-09-05
  • 2021-10-24
  • 2021-12-03
  • 2021-05-19
  • 2021-06-24
  • 2021-09-19
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-06-24
  • 2022-12-23
  • 2021-05-22
  • 2022-12-23
  • 2021-12-13
  • 2021-12-09
相关资源
相似解决方案