1 package be
.nikiroo
.utils
;
3 import java
.io
.IOException
;
4 import java
.io
.InputStream
;
5 import java
.io
.UnsupportedEncodingException
;
7 public class ReplaceInputStream
extends BufferedInputStream
{
11 private byte[] source
;
15 public ReplaceInputStream(InputStream in
, String from
, String to
) {
16 this(in
, bytes(from
), bytes(to
));
19 public ReplaceInputStream(InputStream in
, byte[] from
, byte[] to
) {
24 source
= new byte[4096];
30 protected int read(InputStream in
, byte[] buffer
) throws IOException
{
31 if (buffer
.length
< to
.length
) {
32 throw new IOException(
33 "Underlaying buffer is too small to contain the replace String");
38 slen
= in
.read(source
);
41 // Note: very simple, not efficient implementation, sorry.
44 while (i
< slen
&& count
< buffer
.length
- to
.length
) {
45 if (from
.length
> 0 && startsWith(from
, source
, spos
)) {
46 System
.arraycopy(to
, 0, buffer
, spos
, to
.length
);
51 buffer
[count
++] = source
[i
++];
59 static private byte[] bytes(String str
) {
61 return str
.getBytes("UTF-8");
62 } catch (UnsupportedEncodingException e
) {
63 // All conforming JVM must support UTF-8