Java中ByteArrayInputStream和ByteArrayOutputStream用法详解

Java中ByteArrayInputStream和ByteArrayOutputStream用法详解

这篇文章主要介绍了Java中ByteArrayInputStream和ByteArrayOutputStream用法详解, ByteArrayInputStream 的内部额外的定义了一个计数器,它被用来跟踪 read() 方法要读取的下一个字节

ByteArrayInputStream

介绍ByteArrayInputStream 是字节数组输入流。它继承于 InputStream。

InputStream 通过read()向外提供接口,供它们来读取字节数据;而 ByteArrayInputStream 的内部额外的定义了一个计数器,它被用来跟踪 read() 方法要读取的下一个字节。

它包含一个内部缓冲区,该缓冲区包含从流中读取的字节。也就是说,它内部维护一个数组,输出的数据会放入它内部数组中。

创建对象接收字节数组作为参数创建:

ByteArrayInputStream bArray = ``new` `ByteArrayInputStream(``byte` `[] a);

接收一个字节数组,off 表示第一个读取的字节,len 表示读取字节的长度。

ByteArrayInputStream bArray = new ByteArrayInputStream(byte []a,int off, int len)

InputStream 方法:

函数 返回值 功能
public int read() throws IOEXception 返回下一个数据字节(返回 0255 范围内的 int 字节值) 从输入流中读取数据的下一个字节
public int read(byte[] b) throws IOEXception 以整数形式返回实际读取的字节数。如果因为已经到达流末尾而不再有数据可用,则返回 -1 从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b
public int read(byte[] b,int off,int len) throws IOEXception 读入缓冲区的总字节数;如果因为已到达流末尾而不再有数据可用,则返回 -1 将输入流中最多 len 个数据字节读入 byte 数
public long skip(long n) throws IOEXception 跳过的实际字节数 跳过和丢弃此输入流中数据的 n 个字
public int available() throws IOEXception 可以不受阻塞地从此输入流读取(或跳过)的估计字节数 返回此输入流下一个方法调用可以不受阻塞地从此输入流读取(或跳过)的估计字节数
public boolean markSupported() 如果此输入流实例支持 mark 和 reset 方法,则返回 true;否则返回 false 测试此输入流是否支持 markreset 方法
public void mark(int readlimit) 在此输入流中标记当前的位置
public void reset() throws IOEXception 将此流重新定位到最后一次对此输入流调用 mark 方法时的位置
public void close() throws IOEXception 关闭此输入流并释放与该流关联的所有系统资源

ByteArrayOutputStream

创建对象下面的构造方法创建一个 32 字节(默认大小)的缓冲区

OutputStream bOut = ``new` `ByteArrayOutputStream();

一个构造方法创建一个大小为 a 字节的缓冲区

OutputStream bOut = ``new` `ByteArrayOutputStream(``int` `a)

方法:

序号 方法描述
1 public void reset() 将此字节数组输出流的 count 字段重置为零,从而丢弃输出流中目前已累积的所有数据输出。
2 public byte[] toByteArray() 创建一个新分配的字节数组。数组的大小和当前输出流的大小,内容是当前输出流的拷贝。
3 public String toString() 将缓冲区的内容转换为字符串,根据平台的默认字符编码将字节转换成字符。
4 public void write(int w) 将指定的字节写入此字节数组输出流。
5 public void write(byte []b, int off, int len) 将指定字节数组中从偏移量 off 开始的 len 个字节写入此字节数组输出流。
6 public void writeTo(OutputStream outSt) 将此字节数组输出流的全部内容写入到指定的输出流参数中。

栗子:

public class Main {
    
    
    public static void main(String[] args) throws Exception {
    
    
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        //字节值被放入内部数组
        out.write("abc中文".getBytes());
        //close()是空方法,因为是内存操作,所以没有要关闭的资源,不调用也可以
        //但一般养成习惯写close()方法
        out.close();

        byte[] a = out.toByteArray();
        System.out.println(Arrays.toString(a));

        InputStreamReader in = new InputStreamReader(
                new ByteArrayInputStream(a));
        int c;
        while ((c = in.read()) != -1) {
    
    
            System.out.println((char) c);
        }
        in.close();
    }
}

运行结果:

img

猜你喜欢

转载自blog.csdn.net/qq_43842093/article/details/127311907