Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one or more
   * contributor license agreements.  See the NOTICE file distributed with
   * this work for additional information regarding copyright ownership.
   * The ASF licenses this file to You under the Apache License, Version 2.0
   * (the "License"); you may not use this file except in compliance with
   * the License.  You may obtain a copy of the License at
   * 
   *      http://www.apache.org/licenses/LICENSE-2.0
  * 
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 package org.apache.tomcat.util.http.fileupload;
  
 import static org.jboss.web.FileUploadMessages.MESSAGES;
 
 import java.util.List;

This class implements an output stream in which the data is written into a byte array. The buffer automatically grows as data is written to it.

The data can be retrieved using toByteArray() and toString().

Closing a ByteArrayOutputStream has no effect. The methods in this class can be called after the stream has been closed without generating an IOException.

This is an alternative implementation of the java.io.ByteArrayOutputStream class. The original implementation only allocates 32 bytes at the beginning. As this class is designed for heavy duty it starts at 1024 bytes. In contrast to the original it doesn't reallocate the whole memory block but allocates additional buffers. This way no buffers need to be garbage collected and the contents don't have to be copied to the new buffer. This class is designed to behave exactly like the original. The only exception is the deprecated toString(int) method that has been ignored.

Author(s):
Jeremias Maerki
Holger Hoffstatte
Version:
$Id: ByteArrayOutputStream.java 881562 2009-11-17 22:03:22Z markt $
 
 public class ByteArrayOutputStream extends OutputStream {

    
A singleton empty byte array.
 
     private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];

    
The list of buffers, which grows and never reduces.
 
     private List<byte[]> buffers = new ArrayList<byte[]>();
    
The index of the current buffer.
 
     private int currentBufferIndex;
    
The total count of bytes in all the filled buffers.
 
     private int filledBufferSum;
    
The current buffer.
 
     private byte[] currentBuffer;
    
The total count of bytes written.
 
     private int count;

    
Creates a new byte array output stream. The buffer capacity is initially 1024 bytes, though its size increases if necessary.
 
     public ByteArrayOutputStream() {
         this(1024);
     }

    
Creates a new byte array output stream, with a buffer capacity of the specified size, in bytes.

Parameters:
size the initial size
Throws:
java.lang.IllegalArgumentException if size is negative
 
     public ByteArrayOutputStream(int size) {
         if (size < 0) {
             throw .negativeBufferSize(size);
         }
         needNewBuffer(size);
     }

    
Return the appropriate byte[] buffer specified by index.

Parameters:
index the index of the buffer required
Returns:
the buffer
 
     private byte[] getBuffer(int index) {
         return .get(index);
    }

    
Makes a new buffer available either by allocating a new one or re-cycling an existing one.

Parameters:
newcount the size of the buffer if one is created
    private void needNewBuffer(int newcount) {
        if ( < .size() - 1) {
            //Recycling old buffer
             += .;
            
            ++;
             = getBuffer();
        } else {
            //Creating new buffer
            int newBufferSize;
            if ( == null) {
                newBufferSize = newcount;
                 = 0;
            } else {
                newBufferSize = Math.max(
                    . << 1, 
                    newcount - );
                 += .;
            }
            
            ++;
             = new byte[newBufferSize];
            .add();
        }
    }

    
Write the bytes to byte array.

Parameters:
b the bytes to write
off The start offset
len The number of bytes to write
    @Override
    public void write(byte[] bint offint len) {
        if ((off < 0) 
                || (off > b.length
                || (len < 0) 
                || ((off + len) > b.length
                || ((off + len) < 0)) {
            throw new IndexOutOfBoundsException();
        } else if (len == 0) {
            return;
        }
        synchronized (this) {
            int newcount =  + len;
            int remaining = len;
            int inBufferPos =  - ;
            while (remaining > 0) {
                int part = Math.min(remaining. - inBufferPos);
                System.arraycopy(boff + len - remaininginBufferPospart);
                remaining -= part;
                if (remaining > 0) {
                    needNewBuffer(newcount);
                    inBufferPos = 0;
                }
            }
             = newcount;
        }
    }

    
Write a byte to byte array.

Parameters:
b the byte to write
    @Override
    public synchronized void write(int b) {
        int inBufferPos =  - ;
        if (inBufferPos == .) {
            needNewBuffer( + 1);
            inBufferPos = 0;
        }
        [inBufferPos] = (byteb;
        ++;
    }

    
Writes the entire contents of the specified input stream to this byte stream. Bytes from the input stream are read directly into the internal buffers of this streams.

Parameters:
in the input stream to read from
Returns:
total number of bytes read from the input stream (and written to this stream)
Throws:
java.io.IOException if an I/O error occurs while reading the input stream
Since:
Commons IO 1.4
    public synchronized int write(InputStream inthrows IOException {
        int readCount = 0;
        int inBufferPos =  - ;
        int n = in.read(inBufferPos. - inBufferPos);
        while (n != -1) {
            readCount += n;
            inBufferPos += n;
             += n;
            if (inBufferPos == .) {
                needNewBuffer(.);
                inBufferPos = 0;
            }
            n = in.read(inBufferPos. - inBufferPos);
        }
        return readCount;
    }

    
Return the current size of the byte array.

Returns:
the current size of the byte array
    public synchronized int size() {
        return ;
    }

    
Closing a ByteArrayOutputStream has no effect. The methods in this class can be called after the stream has been closed without generating an IOException.

Throws:
java.io.IOException never (this method should not declare this exception but it has to now due to backwards compatability)
    @Override
    public void close() throws IOException {
        //nop
    }

    
    public synchronized void reset() {
         = 0;
         = 0;
         = 0;
    }

    
Writes the entire contents of this byte stream to the specified output stream.

Parameters:
out the output stream to write to
Throws:
java.io.IOException if an I/O error occurs, such as if the stream is closed
See also:
java.io.ByteArrayOutputStream.writeTo(java.io.OutputStream)
    public synchronized void writeTo(OutputStream outthrows IOException {
        int remaining = ;
        for (int i = 0; i < .size(); i++) {
            byte[] buf = getBuffer(i);
            int c = Math.min(buf.lengthremaining);
            out.write(buf, 0, c);
            remaining -= c;
            if (remaining == 0) {
                break;
            }
        }
    }

    
Gets the curent contents of this byte stream as a byte array. The result is independent of this stream.

Returns:
the current contents of this output stream, as a byte array
See also:
java.io.ByteArrayOutputStream.toByteArray()
    public synchronized byte[] toByteArray() {
        int remaining = ;
        if (remaining == 0) {
            return 
        }
        byte newbuf[] = new byte[remaining];
        int pos = 0;
        for (int i = 0; i < .size(); i++) {
            byte[] buf = getBuffer(i);
            int c = Math.min(buf.lengthremaining);
            System.arraycopy(buf, 0, newbufposc);
            pos += c;
            remaining -= c;
            if (remaining == 0) {
                break;
            }
        }
        return newbuf;
    }

    
Gets the curent contents of this byte stream as a string.

Returns:
the contents of the byte array as a String
See also:
java.io.ByteArrayOutputStream.toString()
    @Override
    public String toString() {
        return new String(toByteArray());
    }

    
Gets the curent contents of this byte stream as a string using the specified encoding.

Parameters:
enc the name of the character encoding
Returns:
the string converted from the byte array
Throws:
java.io.UnsupportedEncodingException if the encoding is not supported
See also:
java.io.ByteArrayOutputStream.toString(java.lang.String)
    public String toString(String encthrows UnsupportedEncodingException {
        return new String(toByteArray(), enc);
    }
New to GrepCode? Check out our FAQ X