public class ReplacingInputStream
extends java.io.FilterInputStream
This class applies replacement rules in particular order based on replacement 'from' data length.
I.e. if this class is provided with replacements like
({1, 2} -> {3, 4}; {2, 3, 4} -> {5, 6, 7}; {4, 5} -> {7, 8}) it guarantees that
'{2, 3, 4} -> {5, 6, 7}' replacement is applied before anothers. Processing order of same
'from'-length replacements is unspecified.
When particular replacement rule is applied, it's 'to' clause is not processed via another
replacement rules. I.e. if we have a mappings like '{1, 2, 3} -> {4, 5, 6}' and
{5} -> {7}, last rule is not applied to the '5' byte that appeared at the
'5, 6, 7' group.
Memory overhead
This class uses internal buffering similar to the one used by PushbackInputStream
and uses a dedicated buffer for single-byte reads (InputStream.read()). I.e. it creates two buffers in
addition to the given stream. One buffer has a size that is max of replacements 'from'
and 'to' buffers size, another is guaranteed to be not more than size of the buffer used by client
for buffered reading (read(byte[], int, int)).
CPU overhead Generally speaking this class matches every read byte against configured replacement rules and performs replacement if necessary.
Not thread-safe.
Example
Map<byte[], byte[]> replacements = new HashMap<byte[],byte[]>();
replacements.put(new byte[] {1, 2}, new byte[] {7, 8});
replacements.put(new byte[] {1}, new byte[] {9});
replacements.put(new byte[] {3, 2}, new byte[0]);
byte[] input = {4, 3, 2, 1, 2, 1, 3};
ReplaceFilterInputStream in = new ReplaceFilterInputStream(new ByteArrayInputStream(input), replacements);
ByteArrayOutputStream out = new ByteArrayOutputStream();
int read;
while ((read = in.read()) >= 0) {
out.write(read);
}
System.out.println(Arrays.toString(out.toByteArray())); // prints [4, 7, 8, 9, 3]
| Constructor and Description |
|---|
ReplacingInputStream(java.io.InputStream in,
java.util.Map<byte[],byte[]> replacements)
Creates new
ReplacementInputStream object. |
| Modifier and Type | Method and Description |
|---|---|
int |
read() |
int |
read(byte[] b,
int off,
int len) |
public ReplacingInputStream(java.io.InputStream in,
java.util.Map<byte[],byte[]> replacements)
throws java.lang.IllegalArgumentException
ReplacementInputStream object.in - input stream which content should be replaced if necessaryreplacements - replacements to use with the given input stream; may be empty map,
may not be nulljava.lang.IllegalArgumentException - if given input stream to process or 'replacements' argument
is null