001/*
002 * Copyright (C) 2012 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.io;
018
019import static com.google.common.base.Preconditions.checkNotNull;
020
021import java.io.BufferedWriter;
022import java.io.IOException;
023import java.io.Reader;
024import java.io.Writer;
025import java.nio.charset.Charset;
026
027/**
028 * A destination to which characters can be written, such as a text file. Unlike a {@link Writer}, a
029 * {@code CharSink} is not an open, stateful stream that can be written to and closed. Instead, it
030 * is an immutable <i>supplier</i> of {@code Writer} instances.
031 *
032 * <p>{@code CharSink} provides two kinds of methods:
033 * <ul>
034 *   <li><b>Methods that return a writer:</b> These methods should return a <i>new</i>,
035 *   independent instance each time they are called. The caller is responsible for ensuring that the
036 *   returned writer is closed.
037 *   <li><b>Convenience methods:</b> These are implementations of common operations that are
038 *   typically implemented by opening a writer using one of the methods in the first category,
039 *   doing something and finally closing the writer that was opened.
040 * </ul>
041 *
042 * <p>Any {@link ByteSink} may be viewed as a {@code CharSink} with a specific {@linkplain Charset
043 * character encoding} using {@link ByteSink#asCharSink(Charset)}. Characters written to the
044 * resulting {@code CharSink} will written to the {@code ByteSink} as encoded bytes.
045 *
046 * @since 14.0
047 * @author Colin Decker
048 */
049public abstract class CharSink implements OutputSupplier<Writer> {
050
051  /**
052   * Opens a new {@link Writer} for writing to this sink. This method should return a new,
053   * independent writer each time it is called.
054   *
055   * <p>The caller is responsible for ensuring that the returned writer is closed.
056   *
057   * @throws IOException if an I/O error occurs in the process of opening the writer
058   */
059  public abstract Writer openStream() throws IOException;
060
061  /**
062   * This method is a temporary method provided for easing migration from suppliers to sources and
063   * sinks.
064   *
065   * @since 15.0
066   * @deprecated This method is only provided for temporary compatibility with the
067   *     {@link OutputSupplier} interface and should not be called directly. Use
068   *     {@link #openStream} instead.
069   */
070  @Override
071  @Deprecated
072  public final Writer getOutput() throws IOException {
073    return openStream();
074  }
075
076  /**
077   * Opens a new buffered {@link Writer} for writing to this sink. The returned stream is not
078   * required to be a {@link BufferedWriter} in order to allow implementations to simply delegate
079   * to {@link #openStream()} when the stream returned by that method does not benefit from
080   * additional buffering. This method should return a new, independent writer each time it is
081   * called.
082   *
083   * <p>The caller is responsible for ensuring that the returned writer is closed.
084   *
085   * @throws IOException if an I/O error occurs in the process of opening the writer
086   * @since 15.0 (in 14.0 with return type {@link BufferedWriter})
087   */
088  public Writer openBufferedStream() throws IOException {
089    Writer writer = openStream();
090    return (writer instanceof BufferedWriter)
091        ? (BufferedWriter) writer
092        : new BufferedWriter(writer);
093  }
094
095  /**
096   * Writes the given character sequence to this sink.
097   *
098   * @throws IOException if an I/O error in the process of writing to this sink
099   */
100  public void write(CharSequence charSequence) throws IOException {
101    checkNotNull(charSequence);
102
103    Closer closer = Closer.create();
104    try {
105      Writer out = closer.register(openStream());
106      out.append(charSequence);
107      out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330
108    } catch (Throwable e) {
109      throw closer.rethrow(e);
110    } finally {
111      closer.close();
112    }
113  }
114
115  /**
116   * Writes the given lines of text to this sink with each line (including the last) terminated with
117   * the operating system's default line separator. This method is equivalent to
118   * {@code writeLines(lines, System.getProperty("line.separator"))}.
119   *
120   * @throws IOException if an I/O error occurs in the process of writing to this sink
121   */
122  public void writeLines(Iterable<? extends CharSequence> lines) throws IOException {
123    writeLines(lines, System.getProperty("line.separator"));
124  }
125
126  /**
127   * Writes the given lines of text to this sink with each line (including the last) terminated with
128   * the given line separator.
129   *
130   * @throws IOException if an I/O error occurs in the process of writing to this sink
131   */
132  public void writeLines(Iterable<? extends CharSequence> lines, String lineSeparator)
133      throws IOException {
134    checkNotNull(lines);
135    checkNotNull(lineSeparator);
136
137    Closer closer = Closer.create();
138    try {
139      Writer out = closer.register(openBufferedStream());
140      for (CharSequence line : lines) {
141        out.append(line).append(lineSeparator);
142      }
143      out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330
144    } catch (Throwable e) {
145      throw closer.rethrow(e);
146    } finally {
147      closer.close();
148    }
149  }
150
151  /**
152   * Writes all the text from the given {@link Readable} (such as a {@link Reader}) to this sink.
153   * Does not close {@code readable} if it is {@code Closeable}.
154   *
155   * @throws IOException if an I/O error occurs in the process of reading from {@code readable} or
156   *     writing to this sink
157   */
158  public long writeFrom(Readable readable) throws IOException {
159    checkNotNull(readable);
160
161    Closer closer = Closer.create();
162    try {
163      Writer out = closer.register(openStream());
164      long written = CharStreams.copy(readable, out);
165      out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330
166      return written;
167    } catch (Throwable e) {
168      throw closer.rethrow(e);
169    } finally {
170      closer.close();
171    }
172  }
173}