JAVA基础知识之ByteArrayOutputStream流

一、ByteArrayOutputStream流定义

     API说明:此类实现一个字节输出流、其中数据被写入到字节数组中, 缓冲区在数据写入时会自动增长,关闭该流无效,关闭此流后调用方法不会有异常

二、ByteArrayOutputStream流实例域

/**
     * 存储数据的缓冲区
     */
    protected byte buf[];

    /**
     * 缓冲区中的有效字节数
     */
    protected int count;

三、ByteArrayOutputStream流构造函数

 /**
     * 创建新的字节数组输出流、默认缓冲区大小是32个字节
     */
    public ByteArrayOutputStream() {
        this(32);
    }

    /**
     * 创建新的字节数组输出流,以指定的大小
     */
    public ByteArrayOutputStream(int size) {
        if (size < 0) {
            throw new IllegalArgumentException("Negative initial size: "
                                               + size);
        }
        buf = new byte[size];
    }

四、ByteArrayOutputStream流方法

1)write(int b):写入指定的字节到此字节输出流中

   /**
     * 写入指定的字节到此字节输出流中
     */
    public synchronized void write(int b) {
        ensureCapacity(count + 1);
        buf[count] = (byte) b;
        count += 1;
    }

2)write(byte b[], int off, int len):从指定数组的下标off开始写入len个字节到该输出流中

 /**
     *  从指定数组的下标off开始写入len个字节到该输出流中
     */
    public synchronized void write(byte b[], int off, int len) {
        if ((off < 0) || (off > b.length) || (len < 0) ||
            ((off + len) - b.length > 0)) {
            throw new IndexOutOfBoundsException();
        }
        ensureCapacity(count + len);
        System.arraycopy(b, off, buf, count, len);
        count += len;
    }

3)writeTo(OutputStream out):将此字节输出流的内容写入到指定的输出流中

    /**
     *  将此字节输出流的内容写入到指定的输出流中
     */
    public synchronized void writeTo(OutputStream out) throws IOException {
        out.write(buf, 0, count);
    }

4)reset():重置此字节输出流,废弃此前存储的数据

     /**
     * 重置此字节输出流,废弃此前存储的数据
     */
    public synchronized void reset() {
        count = 0;
    }

5)对输出流的数据进行检索

   /**
     * 将此输出流转成字节数组输出
     */
    public synchronized byte toByteArray()[] {
        return Arrays.copyOf(buf, count);
    }

    /**
     * 将此输出流转成字符串输出
     */
    public synchronized String toString() {
        return new String(buf, 0, count);
    }
    

    /**
     *  通过指定编码格式将缓冲区内容转换为字符串
     */
    public synchronized String toString(String charsetName)
        throws UnsupportedEncodingException
    {
        return new String(buf, 0, count, charsetName);
    }
    
    

6) close():关闭流无效,关闭后调用其他方法不会有异常

    /**
     * 关闭流无效,关闭后调用其他方法不会有异常
     */
    public void close() throws IOException {
    }

五、ByteArrayOutputStream流的作用

    暂时未使用过、所以不清楚项目中什么地方使用,因此暂时了解其功能即可

  • 6
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值