AppendableOutputStream.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.io.output;

  18. import java.io.IOException;
  19. import java.io.OutputStream;
  20. import java.io.Writer;

  21. /**
  22.  * OutputStream implementation that writes the data to an {@link Appendable}
  23.  * Object.
  24.  * <p>
  25.  * For example, can be used with any {@link Writer} or a {@link StringBuilder}
  26.  * or {@link StringBuffer}.
  27.  * </p>
  28.  *
  29.  * @since 2.5
  30.  * @see Appendable
  31.  * @param <T> The type of the {@link Appendable} wrapped by this AppendableOutputStream.
  32.  */
  33. public class AppendableOutputStream <T extends Appendable> extends OutputStream {

  34.     private final T appendable;

  35.     /**
  36.      * Constructs a new instance with the specified appendable.
  37.      *
  38.      * @param appendable the appendable to write to
  39.      */
  40.     public AppendableOutputStream(final T appendable) {
  41.         this.appendable = appendable;
  42.     }

  43.     /**
  44.      * Gets the target appendable.
  45.      *
  46.      * @return the target appendable
  47.      */
  48.     public T getAppendable() {
  49.         return appendable;
  50.     }

  51.     /**
  52.      * Write a character to the underlying appendable.
  53.      *
  54.      * @param b the character to write
  55.      * @throws IOException upon error
  56.      */
  57.     @Override
  58.     public void write(final int b) throws IOException {
  59.         appendable.append((char) b);
  60.     }

  61. }