当前位置: 代码迷 >> 综合 >> Java IO (3) -- ByteArrayInputStream 类
  详细解决方案

Java IO (3) -- ByteArrayInputStream 类

热度:40   发布时间:2023-12-16 13:27:41.0

文章目录

    • 1. 概念
    • 2. 字段
    • 3. 方法
      • 1. 构造器
    • 2. 其他方法
    • 4. 案例

1. 概念

ByteArrayInputStream 在内存中创建一个字节数组缓冲区,从流中读取的字节会保存到该缓冲区中。

2. 字段

  1. protected byte buf[]:保存字节输入流数据的字节数组
  2. protected int pos:读取数组中的下一个字节的索引,是一个正整数,大小在0到count
  3. protected int mark = 0:标记的索引.可通过mark()方法和reset()方法进行设置,不设置的时候,调用第一个构造方法时值为0,调用第二个构造方法时mark值被设置成offset
  4. protected int count:字节流的长度.当用第一个构造方法时,长度是字节数组buf的length,当用第二个构造方法时,长度是offset+length和buf.length的中的较小值

3. 方法

1. 构造器

  1. public ByteArrayInputStream(byte buf[]):接收字节数组 buf
  2. public ByteArrayInputStream(byte buf[], int offset, int length):读取 buf 数组中从 offset 到 offset+length 之间数据

2. 其他方法

  1. public synchronized int read():读取下一个字节,如果已经读取完,将会返回-1
  2. public synchronized int read(byte b[], int off, int len):读取字节数组b,off位置开始,长度为len的数据
  3. public synchronized long skip(long n):跳过字节流流中n个字节,注意是跳过不是跳到
  4. public synchronized int available():返回剩余可读字节数量
  5. public boolean markSupported():是否支持 mark()/reset().这个值总是返回true
  6. public void mark(int readAheadLimit):标记当前的位置,readAheadLimit在此处没有意义
  7. public synchronized void reset():将缓冲区的位置重置到 mark 标记的位置
  8. public void close() throws IOException:关闭流.在流已经关闭的情况,调用字节输入流中的其他方法,不会抛出异常

4. 案例

public class ByteArrayInputStreamDemo {
    public static void main(String[] args) {
    byte[] bytes = "abcdefghijklmnopqrst".getBytes();ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes);//avaiable表示剩余可字节数,除了a,还剩19个字节if(byteStream.available()>0) {
    System.out.println((char)byteStream.read()+"------剩余可读字节数="+byteStream.available());}for(int i  = 0 ; i < 3;i++) {
    if(byteStream.available()>0) {
    System.out.println((char)byteStream.read());}}//现在位置是d,跳过3个字节,下一个字节是hlong skip = byteStream.skip(3);System.out.println((char)byteStream.read()+"-----跳过字节数="+skip);if(byteStream.markSupported()) {
    System.out.println("support mark");}//现在是位置在i,进行标记.byteStream.mark(0);//使用字节数组,一次性读取三个字节.byte[] byteArray = new byte[3];byteStream.read(byteArray, 0, 2);System.out.println(new String(byteArray));//通过reset()方法将指针指到到mark位置byteStream.reset();System.out.println((char)byteStream.read());}
}
//结果
a------剩余可读字节数=19
b
c
d
h-----跳过字节数=3
support mark
ij
i
  相关解决方案