日期:2014-05-16 浏览次数:20552 次
public abstract void write(byte[] b, int off, int len); public abstract void write(int b); public abstract int pipe( OutputStream out );
    // 写入数据到缓冲区
    public void write(byte[] b, int off, int len){
        // 保证缓冲区空间足够
        // 不够则开辟新的空间
        _ensure( len );
        // 复制数据到缓冲区
        System.arraycopy( b , off , _buffer , _cur , len );
        // 改变代表偏移量和缓冲区大小的数字
        _cur += len;
        _size = Math.max( _cur , _size );
    }
    // 保证缓冲区空间足够
    // 不够则开辟新的空间
    void _ensure( int more ){
        // 计算需要的大小
        final int need = _cur + more;
        // 目前的缓冲区大小足够。
        // 不再开辟新的空间
        if ( need < _buffer.length )
            return;
        // 新的缓冲区大小是原来的两倍
        int newSize = _buffer.length*2;
        // 如果仍然不够,开辟更大的空间
        if ( newSize <= need )
            newSize = need + 128;
        // 创建数组
        byte[] n = new byte[newSize];
        // 将缓冲区中数据复制到数组中
        System.arraycopy( _buffer , 0 , n , 0 , _size );
        // 以新的数组作为缓冲区
        _buffer = n;
    }
    // 只写入一个字节
    public void write(int b){
        // 保证有一个字节的空间
        _ensure(1);
        // 将 int 型数据的低 8 位保存到缓冲区
        _buffer[_cur++] = (byte)(0xFF&b);
        // 修改表示缓冲区数据大小的数值
        _size = Math.max( _cur , _size );
    }
    public int pipe( OutputStream out )
        throws IOException {
        // 将缓冲区中的数据写入输出流中
        out.write( _buffer , 0 , _size );
        // 返回缓冲区大小
        return _size;
    }
    public void write(byte[] b, int off, int len){
        while ( len > 0 ){
            // 获取一块当前缓冲区空间
            byte[] bs = _cur();
            // 计算本次写入大小
            int space = Math.min( bs.length - _cur.y , len );
            // 将数据复制缓冲区
            System.arraycopy( b , off , bs , _cur.y , space );
            // 修改偏移量等后续工作
            _cur.inc( space );
            len -= space;
            off += space;
            // 其他后续处理
            // 如缓冲区满时,创建下一个缓冲区块等
            _afterWrite();
        }
    }
    // 只写入一个字节
    public void write(int b){
        // 获取缓冲区空间
        byte[] bs = _cur();
        // 将 int 型数值的低 8 为保存到缓冲区
        bs[_cur.getAndInc()] = (byte)(b&0xFF);
        // 后续处理
        _afterWrite();
    }
    public int pipe( OutputStream out )
        throws IOException {
        
        if ( out == null )
            throw new NullPointerException( "out is null" );
        int total = 0;
        
        for ( int i=-1; i<_fromPool.size(); i++ ){
            // 获取对象池中指定索引的数据
            byte[] b = _get( i );
            // 获取对象池中指定索引的数据的大小
            int amt = _end.len( i );
            // 将数据写入到输出流中
            out.write( b , 0 , amt );
            // 增加表示总数据大小的数值
            total += amt;
        }
        
        return total;
    }