samples/delegatingwriter/src/org/apidesign/delegatingwriter/ExBufferedWriter.java
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/samples/delegatingwriter/src/org/apidesign/delegatingwriter/ExBufferedWriter.java Sat Jun 14 09:53:02 2008 +0200
1.3 @@ -0,0 +1,51 @@
1.4 +/*
1.5 + * To change this template, choose Tools | Templates
1.6 + * and open the template in the editor.
1.7 + */
1.8 +
1.9 +package org.apidesign.delegatingwriter;
1.10 +
1.11 +import java.io.BufferedWriter;
1.12 +import java.io.IOException;
1.13 +import java.io.Writer;
1.14 +
1.15 +/**
1.16 + * This is a regular {@link BufferedWriter}, just it optimizes for
1.17 + * huge {@link CharSequence} objects set to its {@link #append} method.
1.18 + * Instead of converting them to string, which might required too much
1.19 + * temporary memory, it delegates it directly.
1.20 + * <p>
1.21 + * This class is <q>simulating</q> would would happen if JDK's BufferedWriter
1.22 + * in revision 1.5
1.23 + * was designed to delegate its newly added <code>append</code> methods
1.24 + * instead of calling its already existing <code>write</code> ones.
1.25 + *
1.26 + * @author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
1.27 + */
1.28 +public class ExBufferedWriter extends BufferedWriter {
1.29 + private final Writer out;
1.30 +
1.31 + public ExBufferedWriter(Writer out, int sz, boolean optimized) {
1.32 + super(out, sz);
1.33 + this.out = optimized ? out : null;
1.34 + }
1.35 +
1.36 + @Override
1.37 + public Writer append(CharSequence csq) throws IOException {
1.38 + if (out != null) {
1.39 + // efficient, yet dangerous delegation skipping methods known to
1.40 + // subclasses that used version 1.4
1.41 + out.append(csq);
1.42 + return this;
1.43 + } else {
1.44 + // non-efficient variant of delegating via converting to String first
1.45 + // and using one of methods that existed in 1.4
1.46 + if (csq == null) {
1.47 + write("null");
1.48 + } else {
1.49 + write(csq.toString());
1.50 + }
1.51 + return this;
1.52 + }
1.53 + }
1.54 +}