changelog.md
[nikiroo-utils.git] / src / be / nikiroo / utils / streams / ReplaceOutputStream.java
CommitLineData
c8ce09c4
NR
1package be.nikiroo.utils.streams;
2
3import java.io.IOException;
4import java.io.OutputStream;
5
6/**
7 * This {@link OutputStream} will change some of its content by replacing it
8 * with something else.
9 *
10 * @author niki
11 */
12public class ReplaceOutputStream extends BufferedOutputStream {
13 private byte[] from;
14 private byte[] to;
15
16 /**
17 * Create a {@link ReplaceOutputStream} that will replace <tt>from</tt> with
18 * <tt>to</tt>.
19 *
20 * @param out
21 * the under-laying {@link OutputStream}
22 * @param from
23 * the {@link String} to replace
24 * @param to
25 * the {@link String} to replace with
26 */
27 public ReplaceOutputStream(OutputStream out, String from, String to) {
28 this(out, StreamUtils.bytes(from), StreamUtils.bytes(to));
29 }
30
31 /**
32 * Create a {@link ReplaceOutputStream} that will replace <tt>from</tt> with
33 * <tt>to</tt>.
34 *
35 * @param out
36 * the under-laying {@link OutputStream}
37 * @param from
38 * the value to replace
39 * @param to
40 * the value to replace with
41 */
42 public ReplaceOutputStream(OutputStream out, byte[] from, byte[] to) {
43 super(out);
44 bypassFlush = false;
45
46 this.from = from;
47 this.to = to;
48 }
49
50 @Override
51 protected void flush(boolean includingSubStream) throws IOException {
52 // Note: very simple, not efficient implementation, sorry.
53 while (start < stop) {
54 if (from.length > 0
55 && StreamUtils.startsWith(from, buffer, start, stop)) {
56 out.write(to);
57 bytesWritten += to.length;
58 start += from.length;
59 } else {
60 out.write(buffer[start++]);
61 bytesWritten++;
62 }
63 }
64
65 start = 0;
66 stop = 0;
67
68 if (includingSubStream) {
69 out.flush();
70 }
71 }
72}