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
{
13 private byte[][] froms
;
15 private int maxToSize
;
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
, StreamUtils
.bytes(from
), StreamUtils
.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
) {
48 this(in
, new byte[][] { from
}, new byte[][] { to
});
52 * Create a {@link ReplaceInputStream} that will replace all <tt>froms</tt>
55 * Note that they will be replaced in order, and that for each <tt>from</tt>
56 * a <tt>to</tt> must correspond.
59 * the under-laying {@link InputStream}
61 * the values to replace
63 * the values to replace with
65 public ReplaceInputStream(InputStream in
, String
[] froms
, String
[] tos
) {
66 this(in
, StreamUtils
.bytes(froms
), StreamUtils
.bytes(tos
));
70 * Create a {@link ReplaceInputStream} that will replace all <tt>froms</tt>
73 * Note that they will be replaced in order, and that for each <tt>from</tt>
74 * a <tt>to</tt> must correspond.
77 * the under-laying {@link InputStream}
79 * the values to replace
81 * the values to replace with
83 public ReplaceInputStream(InputStream in
, byte[][] froms
, byte[][] tos
) {
86 if (froms
.length
!= tos
.length
) {
87 throw new IllegalArgumentException(
88 "For replacing, each FROM must have a corresponding TO");
94 for (int i
= 0; i
< tos
.length
; i
++) {
95 maxToSize
= Math
.max(maxToSize
, tos
[i
].length
);
98 source
= new byte[4096];
104 protected int read(InputStream in
, byte[] buffer
) throws IOException
{
105 if (buffer
.length
< maxToSize
|| source
.length
< maxToSize
* 2) {
106 throw new IOException(
107 "An underlaying buffer is too small for these replace values");
112 slen
= in
.read(source
);
115 // Note: very simple, not efficient implementation, sorry.
117 while (spos
< slen
&& count
< buffer
.length
- maxToSize
) {
118 boolean replaced
= false;
119 for (int i
= 0; i
< froms
.length
; i
++) {
120 if (froms
[i
] != null && froms
[i
].length
> 0
121 && StreamUtils
.startsWith(froms
[i
], source
, spos
, slen
)) {
122 if (tos
[i
] != null && tos
[i
].length
> 0) {
123 System
.arraycopy(tos
[i
], 0, buffer
, spos
, tos
[i
].length
);
124 count
+= tos
[i
].length
;
127 spos
+= froms
[i
].length
;
134 buffer
[count
++] = source
[spos
++];