1 package be
.nikiroo
.utils
.streams
;
3 import java
.io
.IOException
;
4 import java
.io
.InputStream
;
7 * This {@link InputStream} will change some of its content by replacing it with
12 public class ReplaceInputStream
extends BufferedInputStream
{
16 private byte[] source
;
21 * Create a {@link ReplaceInputStream} that will replace <tt>from</tt> with
25 * the under-laying {@link InputStream}
27 * the {@link String} to replace
29 * the {@link String} to replace with
31 public ReplaceInputStream(InputStream in
, String from
, String to
) {
32 this(in
, StreamUtils
.bytes(from
), StreamUtils
.bytes(to
));
36 * Create a {@link ReplaceInputStream} that will replace <tt>from</tt> with
40 * the under-laying {@link InputStream}
42 * the value to replace
44 * the value to replace with
46 public ReplaceInputStream(InputStream in
, byte[] from
, byte[] to
) {
51 source
= new byte[4096];
57 protected int read(InputStream in
, byte[] buffer
) throws IOException
{
58 if (buffer
.length
< to
.length
|| source
.length
< to
.length
* 2) {
59 throw new IOException(
60 "An underlaying buffer is too small for this replace value");
65 slen
= in
.read(source
);
68 // Note: very simple, not efficient implementation, sorry.
70 while (spos
< slen
&& count
< buffer
.length
- to
.length
) {
72 && StreamUtils
.startsWith(from
, source
, spos
, slen
)) {
73 System
.arraycopy(to
, 0, buffer
, spos
, to
.length
);
77 buffer
[count
++] = source
[spos
++];