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 {
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   * Opens a new {@link BufferedWriter} for writing to this sink. This method should return a new,
063   * independent writer each time it is called.
064   *
065   * <p>The caller is responsible for ensuring that the returned writer is closed.
066   *
067   * @throws IOException if an I/O error occurs in the process of opening the writer
068   */
069  public BufferedWriter openBufferedStream() throws IOException {
070    Writer writer = openStream();
071    return (writer instanceof BufferedWriter)
072        ? (BufferedWriter) writer
073        : new BufferedWriter(writer);
074  }
075
076  /**
077   * Writes the given character sequence to this sink.
078   *
079   * @throws IOException if an I/O error in the process of writing to this sink
080   */
081  public void write(CharSequence charSequence) throws IOException {
082    checkNotNull(charSequence);
083
084    Closer closer = Closer.create();
085    try {
086      Writer out = closer.register(openStream());
087      out.append(charSequence);
088    } catch (Throwable e) {
089      throw closer.rethrow(e);
090    } finally {
091      closer.close();
092    }
093  }
094
095  /**
096   * Writes the given lines of text to this sink with each line (including the last) terminated with
097   * the operating system's default line separator. This method is equivalent to
098   * {@code writeLines(lines, System.getProperty("line.separator"))}.
099   *
100   * @throws IOException if an I/O error occurs in the process of writing to this sink
101   */
102  public void writeLines(Iterable<? extends CharSequence> lines) throws IOException {
103    writeLines(lines, System.getProperty("line.separator"));
104  }
105
106  /**
107   * Writes the given lines of text to this sink with each line (including the last) terminated with
108   * the given line separator.
109   *
110   * @throws IOException if an I/O error occurs in the process of writing to this sink
111   */
112  public void writeLines(Iterable<? extends CharSequence> lines, String lineSeparator)
113      throws IOException {
114    checkNotNull(lines);
115    checkNotNull(lineSeparator);
116
117    Closer closer = Closer.create();
118    try {
119      BufferedWriter out = closer.register(openBufferedStream());
120      for (CharSequence line : lines) {
121        out.append(line).append(lineSeparator);
122      }
123    } catch (Throwable e) {
124      throw closer.rethrow(e);
125    } finally {
126      closer.close();
127    }
128  }
129
130  /**
131   * Writes all the text from the given {@link Readable} (such as a {@link Reader}) to this sink.
132   * Does not close {@code readable} if it is {@code Closeable}.
133   *
134   * @throws IOException if an I/O error occurs in the process of reading from {@code readable} or
135   *     writing to this sink
136   */
137  public long writeFrom(Readable readable) throws IOException {
138    checkNotNull(readable);
139
140    Closer closer = Closer.create();
141    try {
142      Writer out = closer.register(openStream());
143      return CharStreams.copy(readable, out);
144    } catch (Throwable e) {
145      throw closer.rethrow(e);
146    } finally {
147      closer.close();
148    }
149  }
150}