X-Git-Url: http://git.nikiroo.be/?a=blobdiff_plain;ds=sidebyside;f=src%2Fbe%2Fnikiroo%2Futils%2Fstreams%2FReplaceOutputStream.java;fp=src%2Fbe%2Fnikiroo%2Futils%2Fstreams%2FReplaceOutputStream.java;h=e889b76ef6b756c20ca1e2e9ecec561c45ea9a55;hb=c8ce09c4dc57142f94afcdc290dd79c4bddf7820;hp=0000000000000000000000000000000000000000;hpb=8e76f6ab13a8a4a651f2518b6c91d5e6424c7922;p=nikiroo-utils.git diff --git a/src/be/nikiroo/utils/streams/ReplaceOutputStream.java b/src/be/nikiroo/utils/streams/ReplaceOutputStream.java new file mode 100644 index 0000000..e889b76 --- /dev/null +++ b/src/be/nikiroo/utils/streams/ReplaceOutputStream.java @@ -0,0 +1,72 @@ +package be.nikiroo.utils.streams; + +import java.io.IOException; +import java.io.OutputStream; + +/** + * This {@link OutputStream} will change some of its content by replacing it + * with something else. + * + * @author niki + */ +public class ReplaceOutputStream extends BufferedOutputStream { + private byte[] from; + private byte[] to; + + /** + * Create a {@link ReplaceOutputStream} that will replace from with + * to. + * + * @param out + * the under-laying {@link OutputStream} + * @param from + * the {@link String} to replace + * @param to + * the {@link String} to replace with + */ + public ReplaceOutputStream(OutputStream out, String from, String to) { + this(out, StreamUtils.bytes(from), StreamUtils.bytes(to)); + } + + /** + * Create a {@link ReplaceOutputStream} that will replace from with + * to. + * + * @param out + * the under-laying {@link OutputStream} + * @param from + * the value to replace + * @param to + * the value to replace with + */ + public ReplaceOutputStream(OutputStream out, byte[] from, byte[] to) { + super(out); + bypassFlush = false; + + this.from = from; + this.to = to; + } + + @Override + protected void flush(boolean includingSubStream) throws IOException { + // Note: very simple, not efficient implementation, sorry. + while (start < stop) { + if (from.length > 0 + && StreamUtils.startsWith(from, buffer, start, stop)) { + out.write(to); + bytesWritten += to.length; + start += from.length; + } else { + out.write(buffer[start++]); + bytesWritten++; + } + } + + start = 0; + stop = 0; + + if (includingSubStream) { + out.flush(); + } + } +}