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.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
040 *   typically 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 */
047public abstract class ByteSink {
048
049  /**
050   * Returns a {@link CharSink} view of this {@code ByteSink} that writes characters to this sink
051   * as bytes encoded with the given {@link Charset charset}.
052   */
053  public CharSink asCharSink(Charset charset) {
054    return new AsCharSink(charset);
055  }
056
057  /**
058   * Opens a new {@link OutputStream} for writing to this sink. This method should return a new,
059   * independent stream each time it is called.
060   *
061   * <p>The caller is responsible for ensuring that the returned stream is closed.
062   *
063   * @throws IOException if an I/O error occurs in the process of opening the stream
064   */
065  public abstract OutputStream openStream() throws IOException;
066
067  /**
068   * Opens a new {@link BufferedOutputStream} for writing to this sink. This method should return a
069   * new, independent stream each time it is called.
070   *
071   * <p>The caller is responsible for ensuring that the returned stream is closed.
072   *
073   * @throws IOException if an I/O error occurs in the process of opening the stream
074   */
075  public BufferedOutputStream openBufferedStream() throws IOException {
076    OutputStream out = openStream();
077    return (out instanceof BufferedOutputStream)
078        ? (BufferedOutputStream) out
079        : new BufferedOutputStream(out);
080  }
081
082  /**
083   * Writes all the given bytes to this sink.
084   *
085   * @throws IOException if an I/O occurs in the process of writing to this sink
086   */
087  public void write(byte[] bytes) throws IOException {
088    checkNotNull(bytes);
089
090    Closer closer = Closer.create();
091    try {
092      OutputStream out = closer.register(openStream());
093      out.write(bytes);
094    } catch (Throwable e) {
095      throw closer.rethrow(e);
096    } finally {
097      closer.close();
098    }
099  }
100
101  /**
102   * Writes all the bytes from the given {@code InputStream} to this sink. Does not close
103   * {@code input}.
104   *
105   * @throws IOException if an I/O occurs in the process of reading from {@code input} or writing to
106   *     this sink
107   */
108  public long writeFrom(InputStream input) throws IOException {
109    checkNotNull(input);
110
111    Closer closer = Closer.create();
112    try {
113      OutputStream out = closer.register(openStream());
114      return ByteStreams.copy(input, out);
115    } catch (Throwable e) {
116      throw closer.rethrow(e);
117    } finally {
118      closer.close();
119    }
120  }
121
122  /**
123   * A char sink that encodes written characters with a charset and writes resulting bytes to this
124   * byte sink.
125   */
126  private final class AsCharSink extends CharSink {
127
128    private final Charset charset;
129
130    private AsCharSink(Charset charset) {
131      this.charset = checkNotNull(charset);
132    }
133
134    @Override
135    public Writer openStream() throws IOException {
136      return new OutputStreamWriter(ByteSink.this.openStream(), charset);
137    }
138
139    @Override
140    public String toString() {
141      return ByteSink.this.toString() + ".asCharSink(" + charset + ")";
142    }
143  }
144}