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