Top Description Inners Fields Constructors Methods
org.springframework.util

public Class FastByteArrayOutputStream

extends OutputStream
Class Inheritance
Imports
java.io.IOException, .InputStream, .OutputStream, java.nio.charset.Charset, java.security.MessageDigest, java.util.ArrayDeque, .Deque, .Iterator, org.springframework.lang.Nullable

A speedy alternative to java.io.ByteArrayOutputStream. Note that this variant does not extend ByteArrayOutputStream, unlike its sibling ResizableByteArrayOutputStream.

Unlike java.io.ByteArrayOutputStream, this implementation is backed by a java.util.ArrayDeque of byte[] buffers instead of one constantly resizing byte[]. It does not copy buffers when it gets expanded.

The initial buffer is only created when the stream is first written. There is also no copying of the internal buffers if the stream's content is extracted via the writeTo(OutputStream) method.

Authors
Craig Andrews, Juergen Hoeller
Since
4.2
See Also
resize, ResizableByteArrayOutputStream

Nested and Inner Type Summary

Modifier and TypeClass and Description
private static class
FastByteArrayOutputStream.FastByteArrayInputStream

An implementation of java.io.InputStream that reads from a given FastByteArrayOutputStream.

Field Summary

Modifier and TypeField and Description
private int
private final Deque<byte[]>
private boolean
private static final int
private int
private final int
private int

Constructor Summary

AccessConstructor and Description
public
FastByteArrayOutputStream()

Create a new FastByteArrayOutputStream with the default initial capacity of 256 bytes.

public
FastByteArrayOutputStream(int
the initial buffer size in bytes
initialBlockSize
)

Create a new FastByteArrayOutputStream with the specified initial capacity.

Method Summary

Modifier and TypeMethod and Description
private void
addBuffer(int minCapacity)

Create a new buffer and store it in the ArrayDeque.

public void
close()

Overrides java.io.OutputStream.close.

Implements java.io.Closeable.close.

Closes this output stream and releases any system resources associated with this stream.

public InputStream

Returns:

InputStream of the contents of this FastByteArrayOutputStream
getInputStream
()

Get an InputStream to retrieve the contents of this FastByteArrayOutputStream.

private static int
nextPowerOf2(int val)

Get the next power of 2 of a number (ex, the next power of 2 of 119 is 128).

public void
reset()

Reset the contents of this FastByteArrayOutputStream.

public void
resize(int
the desired size of the buffer
targetCapacity
)

Resize the internal buffer size to the specified capacity.

public int
size()

Return the number of bytes stored in this FastByteArrayOutputStream.

public byte[]

Returns:

the current contents of this stream as a byte array
toByteArray
()

Create a newly allocated byte array.

public byte[]

Returns:

the current contents of this stream as a byte array
toByteArrayUnsafe
()

Convert this stream's contents to a byte array and return the byte array.

public String

Returns:

a String decoded from this stream's contents
toString
()

Overrides java.lang.Object.toString.

Convert this stream's contents to a string by decoding the bytes using the platform's default character set.

public String

Returns:

a String decoded from this stream's contents
toString
(Charset
the Charset to use to decode the bytes
charset
)

Convert this stream's contents to a string by decoding the bytes using the specified Charset.

public void
write(int
the byte.
datum
)

Implements abstract java.io.OutputStream.write.

Writes the specified byte to this output stream.

public void
write(byte[]
the data.
data
,
int
the start offset in the data.
offset
,
int
the number of bytes to write.
length
)

Overrides java.io.OutputStream.write.

Writes len bytes from the specified byte array starting at offset off to this output stream.

public void
writeTo(OutputStream
the OutputStream to write to
out
)

Write the contents of this FastByteArrayOutputStream to the given OutputStream.

Inherited from java.io.OutputStream:
flushnullOutputStreamwrite

Field Detail

alreadyBufferedSizeback to summary
private int alreadyBufferedSize
buffersback to summary
private final Deque<byte[]> buffers
closedback to summary
private boolean closed
DEFAULT_BLOCK_SIZEback to summary
private static final int DEFAULT_BLOCK_SIZE
indexback to summary
private int index
initialBlockSizeback to summary
private final int initialBlockSize
nextBlockSizeback to summary
private int nextBlockSize

Constructor Detail

FastByteArrayOutputStreamback to summary
public FastByteArrayOutputStream()

Create a new FastByteArrayOutputStream with the default initial capacity of 256 bytes.

FastByteArrayOutputStreamback to summary
public FastByteArrayOutputStream(int initialBlockSize)

Create a new FastByteArrayOutputStream with the specified initial capacity.

Parameters
initialBlockSize:int

the initial buffer size in bytes

Method Detail

addBufferback to summary
private void addBuffer(int minCapacity)

Create a new buffer and store it in the ArrayDeque.

Adds a new buffer that can store at least minCapacity bytes.

closeback to summary
public void close()

Overrides java.io.OutputStream.close.

Implements java.io.Closeable.close.

Doc from java.io.OutputStream.close.

Closes this output stream and releases any system resources associated with this stream. The general contract of close is that it closes the output stream. A closed stream cannot perform output operations and cannot be reopened.

Annotations
@Override
getInputStreamback to summary
public InputStream getInputStream()

Get an InputStream to retrieve the contents of this FastByteArrayOutputStream.

Note that if any methods are called on this FastByteArrayOutputStream (including, but not limited to, any of the write methods, reset(), toByteArray(), and toByteArrayUnsafe()) then the InputStream's behavior is undefined.

Returns:InputStream

InputStream of the contents of this FastByteArrayOutputStream

nextPowerOf2back to summary
private static int nextPowerOf2(int val)

Get the next power of 2 of a number (ex, the next power of 2 of 119 is 128).

resetback to summary
public void reset()

Reset the contents of this FastByteArrayOutputStream.

All currently accumulated output in the output stream is discarded. The output stream can be used again.

resizeback to summary
public void resize(int targetCapacity)

Resize the internal buffer size to the specified capacity.

Parameters
targetCapacity:int

the desired size of the buffer

Exceptions
IllegalArgumentException:
if the given capacity is smaller than the actual size of the content stored in the buffer already
See Also
FastByteArrayOutputStream#size()
sizeback to summary
public int size()

Return the number of bytes stored in this FastByteArrayOutputStream.

toByteArrayback to summary
public byte[] toByteArray()

Create a newly allocated byte array.

Its size is the current size of this output stream, and it will contain the valid contents of the internal buffers.

Returns:byte[]

the current contents of this stream as a byte array

See Also
size(), toByteArrayUnsafe()
toByteArrayUnsafeback to summary
public byte[] toByteArrayUnsafe()

Convert this stream's contents to a byte array and return the byte array.

Also replaces the internal structures with the byte array to conserve memory: if the byte array is being created anyway, we might as well as use it. This approach also means that if this method is called twice without any writes in the interim, the second call is a no-op.

This method is "unsafe" as it returns the internal buffer. Callers should not modify the returned buffer.

Returns:byte[]

the current contents of this stream as a byte array

See Also
size(), toByteArray()
toStringback to summary
public String toString()

Overrides java.lang.Object.toString.

Convert this stream's contents to a string by decoding the bytes using the platform's default character set. The length of the new String is a function of the character set, and hence may not be equal to the size of the buffers.

This method always replaces malformed-input and unmappable-character sequences with the default replacement string for the platform's default character set. The java.nio.charset.CharsetDecoder class should be used when more control over the decoding process is required.

Returns:String

a String decoded from this stream's contents

Annotations
@Override
See Also
toString(Charset)
toStringback to summary
public String toString(Charset charset)

Convert this stream's contents to a string by decoding the bytes using the specified Charset.

Parameters
charset:Charset

the Charset to use to decode the bytes

Returns:String

a String decoded from this stream's contents

Since
6.1.2
See Also
toString()
writeback to summary
public void write(int datum) throws IOException

Implements abstract java.io.OutputStream.write.

Doc from java.io.OutputStream.write.

Writes the specified byte to this output stream. The general contract for write is that one byte is written to the output stream. The byte to be written is the eight low-order bits of the argument b. The 24 high-order bits of b are ignored.

Parameters
datum:int

the byte.

Annotations
@Override
Exceptions
IOException:
if an I/O error occurs. In particular, an IOException may be thrown if the output stream has been closed.
writeback to summary
public void write(byte[] data, int offset, int length) throws IOException

Overrides java.io.OutputStream.write.

Doc from java.io.OutputStream.write.

Writes len bytes from the specified byte array starting at offset off to this output stream. The general contract for write(b, off, len) is that some of the bytes in the array b are written to the output stream in order; element b[off] is the first byte written and b[off+len-1] is the last byte written by this operation.

If b is null, a NullPointerException is thrown.

If off is negative, or len is negative, or off+len is greater than the length of the array b, then an IndexOutOfBoundsException is thrown.

Parameters
data:byte[]

the data.

offset:int

the start offset in the data.

length:int

the number of bytes to write.

Annotations
@Override
Exceptions
IOException:
if an I/O error occurs. In particular, an IOException is thrown if the output stream is closed.
writeToback to summary
public void writeTo(OutputStream out) throws IOException

Write the contents of this FastByteArrayOutputStream to the given OutputStream.

Parameters
out:OutputStream

the OutputStream to write to

org.springframework.util back to summary

private final Class FastByteArrayOutputStream.FastByteArrayInputStream

extends UpdateMessageDigestInputStream
Class Inheritance

An implementation of java.io.InputStream that reads from a given FastByteArrayOutputStream.

Field Summary

Modifier and TypeField and Description
private final Iterator<byte[]>
private byte[]
private int
private final FastByteArrayOutputStream
private int
private int

Constructor Summary

AccessConstructor and Description
public
FastByteArrayInputStream(FastByteArrayOutputStream fastByteArrayOutputStream)

Create a new FastByteArrayInputStream backed by the given FastByteArrayOutputStream.

Method Summary

Modifier and TypeMethod and Description
public int
available()

Overrides java.io.InputStream.available.

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking, which may be 0, or 0 when end of stream is detected.

public int
read()

Implements abstract java.io.InputStream.read.

Reads the next byte of data from the input stream.

public int
read(byte[]
the buffer into which the data is read.
b
)

Overrides java.io.InputStream.read.

Reads some number of bytes from the input stream and stores them into the buffer array b.

public int
read(byte[]
the buffer into which the data is read.
b
,
int
the start offset in array b at which the data is written.
off
,
int
the maximum number of bytes to read.
len
)

Overrides java.io.InputStream.read.

Reads up to len bytes of data from the input stream into an array of bytes.

public long
skip(long
the number of bytes to be skipped.
n
)

Overrides java.io.InputStream.skip.

Skips over and discards n bytes of data from this input stream.

private void
public void
updateMessageDigest(MessageDigest
the message digest to update
messageDigest
)

Overrides org.springframework.util.UpdateMessageDigestInputStream.updateMessageDigest.

Update the message digest with the remaining bytes in this stream.

public void
updateMessageDigest(MessageDigest
the message digest to update
messageDigest
,
int
how many bytes to read from this stream and use to update the message digest
len
)

Overrides org.springframework.util.UpdateMessageDigestInputStream.updateMessageDigest.

Update the message digest with the next len bytes in this stream.

Field Detail

buffersIteratorback to summary
private final Iterator<byte[]> buffersIterator
currentBufferback to summary
private byte[] currentBuffer
Annotations
@Nullable
currentBufferLengthback to summary
private int currentBufferLength
fastByteArrayOutputStreamback to summary
private final FastByteArrayOutputStream fastByteArrayOutputStream
nextIndexInCurrentBufferback to summary
private int nextIndexInCurrentBuffer
totalBytesReadback to summary
private int totalBytesRead

Constructor Detail

FastByteArrayInputStreamback to summary
public FastByteArrayInputStream(FastByteArrayOutputStream fastByteArrayOutputStream)

Create a new FastByteArrayInputStream backed by the given FastByteArrayOutputStream.

Method Detail

availableback to summary
public int available()

Overrides java.io.InputStream.available.

Doc from java.io.InputStream.available.

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking, which may be 0, or 0 when end of stream is detected. The read might be on the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.

Note that while some implementations of InputStream will return the total number of bytes in the stream, many will not. It is never correct to use the return value of this method to allocate a buffer intended to hold all data in this stream.

A subclass's implementation of this method may choose to throw an IOException if this input stream has been closed by invoking the close() method.

Returns:int

an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking or 0 when it reaches the end of the input stream.

Annotations
@Override
readback to summary
public int read()

Implements abstract java.io.InputStream.read.

Doc from java.io.InputStream.read.

Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

Returns:int

the next byte of data, or -1 if the end of the stream is reached.

Annotations
@Override
readback to summary
public int read(byte[] b)

Overrides java.io.InputStream.read.

Doc from java.io.InputStream.read.

Reads some number of bytes from the input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer. This method blocks until input data is available, end of file is detected, or an exception is thrown.

If the length of b is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is at the end of the file, the value -1 is returned; otherwise, at least one byte is read and stored into b.

The first byte read is stored into element b[0], the next one into b[1], and so on. The number of bytes read is, at most, equal to the length of b. Let k be the number of bytes actually read; these bytes will be stored in elements b[0] through b[k-1], leaving elements b[k] through b[b.length-1] unaffected.

Parameters
b:byte[]

the buffer into which the data is read.

Returns:int

the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.

Annotations
@Override
readback to summary
public int read(byte[] b, int off, int len)

Overrides java.io.InputStream.read.

Doc from java.io.InputStream.read.

Reads up to len bytes of data from the input stream into an array of bytes. An attempt is made to read as many as len bytes, but a smaller number may be read. The number of bytes actually read is returned as an integer.

This method blocks until input data is available, end of file is detected, or an exception is thrown.

If len is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is at end of file, the value -1 is returned; otherwise, at least one byte is read and stored into b.

The first byte read is stored into element b[off], the next one into b[off+1], and so on. The number of bytes read is, at most, equal to len. Let k be the number of bytes actually read; these bytes will be stored in elements b[off] through b[off+k-1], leaving elements b[off+k] through b[off+len-1] unaffected.

In every case, elements b[0] through b[off-1] and elements b[off+len] through b[b.length-1] are unaffected.

Parameters
b:byte[]

the buffer into which the data is read.

off:int

the start offset in array b at which the data is written.

len:int

the maximum number of bytes to read.

Returns:int

the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.

Annotations
@Override
skipback to summary
public long skip(long n) throws IOException

Overrides java.io.InputStream.skip.

Doc from java.io.InputStream.skip.

Skips over and discards n bytes of data from this input stream. The skip method may, for a variety of reasons, end up skipping over some smaller number of bytes, possibly 0. This may result from any of a number of conditions; reaching end of file before n bytes have been skipped is only one possibility. The actual number of bytes skipped is returned. If n is negative, the skip method for class InputStream always returns 0, and no bytes are skipped. Subclasses may handle the negative value differently.

Parameters
n:long

the number of bytes to be skipped.

Returns:long

the actual number of bytes skipped which might be zero.

Annotations
@Override
Exceptions
IOException:
if an I/O error occurs.
updateCurrentBufferLengthback to summary
private void updateCurrentBufferLength()
updateMessageDigestback to summary
public void updateMessageDigest(MessageDigest messageDigest)

Overrides org.springframework.util.UpdateMessageDigestInputStream.updateMessageDigest.

Update the message digest with the remaining bytes in this stream.

Parameters
messageDigest:MessageDigest

the message digest to update

Annotations
@Override
updateMessageDigestback to summary
public void updateMessageDigest(MessageDigest messageDigest, int len)

Overrides org.springframework.util.UpdateMessageDigestInputStream.updateMessageDigest.

Update the message digest with the next len bytes in this stream. Avoids creating new byte arrays and use internal buffers for performance.

Parameters
messageDigest:MessageDigest

the message digest to update

len:int

how many bytes to read from this stream and use to update the message digest

Annotations
@Override