net.sf.fmj.utility.ByteBufferOutputStream Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of fmj Show documentation
Show all versions of fmj Show documentation
Freedom for Media in Java
package net.sf.fmj.utility;
import java.io.*;
/**
* Represents a byte array as an OutputStream.
*
* @author Lyubomir Marinov
*/
public class ByteBufferOutputStream
extends OutputStream
{
/**
* The index within {@link #buf} which was initially writable.
*/
private final int beginIndex;
/**
* The byte array represented as an OutputStream by this
* instance.
*/
private final byte[] buf;
/**
* The index right after the last writable index within {@link #buf}.
*/
private final int endIndex;
/**
* The first writable index within {@link #buf}.
*/
private int index;
/**
* Initializes a new ByteBufferOutputStream instance which is to
* represent a specific byte array as an OutputStream.
*
* @param buf the byte array for which the new instance is to
* implement OutputStream
*/
public ByteBufferOutputStream(byte[] buf)
{
this(buf, 0, buf.length);
}
/**
* Initializes a new ByteBufferOutputStream instance which is to
* represent a specific byte array as an OutputStream.
*
* @param buf the byte array for which the new instance is to
* implement OutputStream
* @param off
* @param len
*/
public ByteBufferOutputStream(byte[] buf, int off, int len)
{
if (buf == null)
throw new NullPointerException("buf");
if (off < 0)
throw new IndexOutOfBoundsException("off");
if (len > buf.length)
throw new IndexOutOfBoundsException("len");
this.buf = buf;
this.beginIndex = off;
this.index = off;
this.endIndex = off + len;
}
/**
* Returns the number of bytes written into this OutputStream.
*
* @return the number of bytes written into this OutputStream
*/
public int size()
{
return index - beginIndex;
}
/**
* {@inheritDoc}
*/
@Override
public void write(int b)
throws IOException
{
if (index >= endIndex)
{
throw new IOException(
"This " + ByteBufferOutputStream.class.getName()
+ " is fully written.");
}
else
{
buf[index++] = (byte) b;
}
}
}