1 package be
.nikiroo
.utils
;
3 import java
.io
.IOException
;
4 import java
.io
.InputStream
;
5 import java
.io
.UnsupportedEncodingException
;
8 * This {@link InputStream} will replace some of its content by replacing it
13 public class ReplaceInputStream
extends BufferedInputStream
{
17 private byte[] source
;
22 * Create a {@link ReplaceInputStream} that will replace <tt>from</tt> with
26 * the under-laying {@link InputStream}
28 * the {@link String} to replace
30 * the {@link String} to replace with
32 public ReplaceInputStream(InputStream in
, String from
, String to
) {
33 this(in
, bytes(from
), bytes(to
));
37 * Create a {@link ReplaceInputStream} that will replace <tt>from</tt> with
41 * the under-laying {@link InputStream}
43 * the value to replace
45 * the value to replace with
47 public ReplaceInputStream(InputStream in
, byte[] from
, byte[] to
) {
52 source
= new byte[4096];
58 protected int read(InputStream in
, byte[] buffer
) throws IOException
{
59 if (buffer
.length
< to
.length
|| source
.length
< to
.length
* 2) {
60 throw new IOException(
61 "An underlaying buffer is too small for this replace value");
66 slen
= in
.read(source
);
69 // Note: very simple, not efficient implementation, sorry.
71 while (spos
< slen
&& count
< buffer
.length
- to
.length
) {
72 if (from
.length
> 0 && startsWith(from
, source
, spos
, slen
)) {
73 System
.arraycopy(to
, 0, buffer
, spos
, to
.length
);
77 buffer
[count
++] = source
[spos
++];
85 * Return the bytes array representation of the given {@link String} in
89 * the string to transform into bytes
90 * @return the content in bytes
92 static private byte[] bytes(String str
) {
94 return str
.getBytes("UTF-8");
95 } catch (UnsupportedEncodingException e
) {
96 // All conforming JVM must support UTF-8