Create create a subclass of
RegexOutputStream. This class should buffer all data written to it (from the different
write(...) methods). In the
flush() method, it should apply the regex and then write the result to the underlying
Next, instantiate the
PrintWriter to write to the
RegexOutputStream. This way you don't need to alter the behaviour of the
PrintWriter class. In case you don't want the filtering anymore, you can just take the RegexOutStream out of the chain, and everything will work again.
Note that, depending on how you use the
PrintWriter, this might cause the
RegexOutputStreams buffer to get quite big. If you create the
PrintWriter to autoflush, it will flush after every line and after every byte array. See its JavaDoc for details.