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.errorprone.annotations.CanIgnoreReturnValue;
021import java.io.BufferedOutputStream;
022import java.io.IOException;
023import java.io.InputStream;
024import java.io.OutputStream;
025import java.io.OutputStreamWriter;
026import java.io.Writer;
027import java.nio.charset.Charset;
028
029/**
030 * A destination to which bytes can be written, such as a file. Unlike an {@link OutputStream}, a
031 * {@code ByteSink} is not an open, stateful stream that can be written to and closed. Instead, it
032 * is an immutable <i>supplier</i> of {@code OutputStream} instances.
033 *
034 * <p>{@code ByteSink} provides two kinds of methods:
035 * <ul>
036 * <li><b>Methods that return a stream:</b> These methods should return a <i>new</i>, independent
037 *     instance each time they are called. The caller is responsible for ensuring that the returned
038 *     stream is closed.
039 * <li><b>Convenience methods:</b> These are implementations of common operations that are typically
040 *     implemented by opening a stream using one of the methods in the first category, doing
041 *     something and finally closing the stream or channel that was opened.
042 * </ul>
043 *
044 * @since 14.0
045 * @author Colin Decker
046 */
047@GwtIncompatible
048public abstract class ByteSink {
049
050  /**
051   * Constructor for use by subclasses.
052   */
053  protected ByteSink() {}
054
055  /**
056   * Returns a {@link CharSink} view of this {@code ByteSink} that writes characters to this sink as
057   * bytes encoded with the given {@link Charset charset}.
058   */
059  public CharSink asCharSink(Charset charset) {
060    return new AsCharSink(charset);
061  }
062
063  /**
064   * Opens a new {@link OutputStream} for writing to this sink. This method should return a new,
065   * independent stream each time it is called.
066   *
067   * <p>The caller is responsible for ensuring that the returned stream is closed.
068   *
069   * @throws IOException if an I/O error occurs in the process of opening the stream
070   */
071  public abstract OutputStream openStream() throws IOException;
072
073  /**
074   * Opens a new buffered {@link OutputStream} for writing to this sink. The returned stream is not
075   * required to be a {@link BufferedOutputStream} in order to allow implementations to simply
076   * delegate to {@link #openStream()} when the stream returned by that method does not benefit from
077   * additional buffering (for example, a {@code ByteArrayOutputStream}). This method should return
078   * a new, independent stream each time it is called.
079   *
080   * <p>The caller is responsible for ensuring that the returned stream is closed.
081   *
082   * @throws IOException if an I/O error occurs in the process of opening the stream
083   * @since 15.0 (in 14.0 with return type {@link BufferedOutputStream})
084   */
085  public OutputStream openBufferedStream() throws IOException {
086    OutputStream out = openStream();
087    return (out instanceof BufferedOutputStream)
088        ? (BufferedOutputStream) out
089        : new BufferedOutputStream(out);
090  }
091
092  /**
093   * Writes all the given bytes to this sink.
094   *
095   * @throws IOException if an I/O occurs in the process of writing to this sink
096   */
097  public void write(byte[] bytes) throws IOException {
098    checkNotNull(bytes);
099
100    Closer closer = Closer.create();
101    try {
102      OutputStream out = closer.register(openStream());
103      out.write(bytes);
104      out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330
105    } catch (Throwable e) {
106      throw closer.rethrow(e);
107    } finally {
108      closer.close();
109    }
110  }
111
112  /**
113   * Writes all the bytes from the given {@code InputStream} to this sink. Does not close
114   * {@code input}.
115   *
116   * @return the number of bytes written
117   * @throws IOException if an I/O occurs in the process of reading from {@code input} or writing to
118   *     this sink
119   */
120  @CanIgnoreReturnValue
121  public long writeFrom(InputStream input) throws IOException {
122    checkNotNull(input);
123
124    Closer closer = Closer.create();
125    try {
126      OutputStream out = closer.register(openStream());
127      long written = ByteStreams.copy(input, out);
128      out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330
129      return written;
130    } catch (Throwable e) {
131      throw closer.rethrow(e);
132    } finally {
133      closer.close();
134    }
135  }
136
137  /**
138   * A char sink that encodes written characters with a charset and writes resulting bytes to this
139   * byte sink.
140   */
141  private final class AsCharSink extends CharSink {
142
143    private final Charset charset;
144
145    private AsCharSink(Charset charset) {
146      this.charset = checkNotNull(charset);
147    }
148
149    @Override
150    public Writer openStream() throws IOException {
151      return new OutputStreamWriter(ByteSink.this.openStream(), charset);
152    }
153
154    @Override
155    public String toString() {
156      return ByteSink.this.toString() + ".asCharSink(" + charset + ")";
157    }
158  }
159}