操作数组的流 ByteArrayInputStream 和 ByteArrayOutputStream的简单介绍

来源:互联网 发布:国家网络应急中心 编辑:程序博客网 时间:2024/05/16 12:08

ByteArrayOutputStream 和 ByteArrayinputStream 为类用于操作字节数组。

一、ByteArrayInputStream

构造方法:

   ByteArrayInputStream(byte[] buf);//创建一个带有缓冲字节数据的字节数组输出流

   ByteArrayInputStream(byte[] buf,int off,int len);//创建一个带有缓冲字节数据的字节数组输出流

主要方法:

int read();//返回此输入流的下一个字节

int read(byte []b,intvoff,int len);//将输入流中的len个字节如入到字节数组b中。

二、ByteArrayOutputStream

构造方法:

  ByteArrayOutputStream();

  ByteArratOutputStream(int size);//创建一个指定缓冲区大小的字节数组输出流。

主要方法:

 String toString();//使用平台默认的字符集,通过解码字节将缓冲区内容转换为字符串。

 void write(int ch);//将该字节写入到输出流中。

 void write(byte []b,int off,int len);//将该字节数组blen个字节写入到该输出流中。

代码演示:

package Other;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;public class ByteArrayStreamDemo {/** * @param args * @throws IOException */public static void main(String[] args) throws IOException {show2();}//一个字节字节的从输入流  存到 字节输出流中。public static void show() throws IOException {ByteArrayInputStream bis = new ByteArrayInputStream("abcdefgh".getBytes());ByteArrayOutputStream bos = new ByteArrayOutputStream();int ch = 0;while ((ch = bis.read()) != -1) {bos.write(ch);}System.out.println(bos.toString());}//利用缓冲的方法从输入流  存到 字节输出流中。public static void show2() throws IOException {ByteArrayInputStream bis = new ByteArrayInputStream("abcdnihao".getBytes());ByteArrayOutputStream bos = new ByteArrayOutputStream();byte[] b = new byte[1024];int len;while((len = bis.read(b))!= -1){//将缓冲区的字节数据读入到字节数组b中。bos.write(b, 0, len);//将字节数组b中的数据写到字节数组输出流中。}System.out.println(bos.toString());//将字节数组输出流中的数据打印到控制台。}}