| 1 | package be.nikiroo.utils; |
| 2 | |
| 3 | import java.io.IOException; |
| 4 | import java.io.InputStream; |
| 5 | import java.io.UnsupportedEncodingException; |
| 6 | |
| 7 | public class ReplaceInputStream extends BufferedInputStream { |
| 8 | private byte[] from; |
| 9 | private byte[] to; |
| 10 | |
| 11 | private byte[] source; |
| 12 | private int spos; |
| 13 | private int slen; |
| 14 | |
| 15 | public ReplaceInputStream(InputStream in, String from, String to) { |
| 16 | this(in, bytes(from), bytes(to)); |
| 17 | } |
| 18 | |
| 19 | public ReplaceInputStream(InputStream in, byte[] from, byte[] to) { |
| 20 | super(in); |
| 21 | this.from = from; |
| 22 | this.to = to; |
| 23 | |
| 24 | source = new byte[4096]; |
| 25 | spos = 0; |
| 26 | slen = 0; |
| 27 | } |
| 28 | |
| 29 | @Override |
| 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"); |
| 34 | } |
| 35 | |
| 36 | if (spos >= slen) { |
| 37 | spos = 0; |
| 38 | slen = in.read(source); |
| 39 | } |
| 40 | |
| 41 | // Note: very simple, not efficient implementation, sorry. |
| 42 | int count = 0; |
| 43 | int i = spos; |
| 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); |
| 47 | count += to.length; |
| 48 | i += to.length; |
| 49 | spos += to.length; |
| 50 | } else { |
| 51 | buffer[count++] = source[i++]; |
| 52 | spos++; |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | return count; |
| 57 | } |
| 58 | |
| 59 | static private byte[] bytes(String str) { |
| 60 | try { |
| 61 | return str.getBytes("UTF-8"); |
| 62 | } catch (UnsupportedEncodingException e) { |
| 63 | // All conforming JVM must support UTF-8 |
| 64 | e.printStackTrace(); |
| 65 | return null; |
| 66 | } |
| 67 | } |
| 68 | } |