1/*
2 * Copyright (C) 2012 The Guava Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.google.common.io;
18
19import static com.google.common.base.Preconditions.checkNotNull;
20
21import java.io.BufferedOutputStream;
22import java.io.IOException;
23import java.io.InputStream;
24import java.io.OutputStream;
25import java.io.OutputStreamWriter;
26import java.io.Writer;
27import java.nio.charset.Charset;
28
29/**
30 * A destination to which bytes can be written, such as a file. Unlike an {@link OutputStream}, a
31 * {@code ByteSink} is not an open, stateful stream that can be written to and closed. Instead, it
32 * is an immutable <i>supplier</i> of {@code OutputStream} instances.
33 *
34 * <p>{@code ByteSink} provides two kinds of methods:
35 * <ul>
36 *   <li><b>Methods that return a stream:</b> These methods should return a <i>new</i>, independent
37 *   instance each time they are called. The caller is responsible for ensuring that the returned
38 *   stream is closed.
39 *   <li><b>Convenience methods:</b> These are implementations of common operations that are
40 *   typically implemented by opening a stream using one of the methods in the first category, doing
41 *   something and finally closing the stream or channel that was opened.
42 * </ul>
43 *
44 * @since 14.0
45 * @author Colin Decker
46 */
47public abstract class ByteSink {
48
49  /**
50   * Constructor for use by subclasses.
51   */
52  protected ByteSink() {}
53
54  /**
55   * Returns a {@link CharSink} view of this {@code ByteSink} that writes characters to this sink
56   * as bytes encoded with the given {@link Charset charset}.
57   */
58  public CharSink asCharSink(Charset charset) {
59    return new AsCharSink(charset);
60  }
61
62  /**
63   * Opens a new {@link OutputStream} for writing to this sink. This method should return a new,
64   * independent stream each time it is called.
65   *
66   * <p>The caller is responsible for ensuring that the returned stream is closed.
67   *
68   * @throws IOException if an I/O error occurs in the process of opening the stream
69   */
70  public abstract OutputStream openStream() throws IOException;
71
72  /**
73   * Opens a new buffered {@link OutputStream} for writing to this sink. The returned stream is
74   * not required to be a {@link BufferedOutputStream} in order to allow implementations to simply
75   * delegate to {@link #openStream()} when the stream returned by that method does not benefit
76   * from additional buffering (for example, a {@code ByteArrayOutputStream}). This method should
77   * return a new, independent stream each time it is called.
78   *
79   * <p>The caller is responsible for ensuring that the returned stream is closed.
80   *
81   * @throws IOException if an I/O error occurs in the process of opening the stream
82   * @since 15.0 (in 14.0 with return type {@link BufferedOutputStream})
83   */
84  public OutputStream openBufferedStream() throws IOException {
85    OutputStream out = openStream();
86    return (out instanceof BufferedOutputStream)
87        ? (BufferedOutputStream) out
88        : new BufferedOutputStream(out);
89  }
90
91  /**
92   * Writes all the given bytes to this sink.
93   *
94   * @throws IOException if an I/O occurs in the process of writing to this sink
95   */
96  public void write(byte[] bytes) throws IOException {
97    checkNotNull(bytes);
98
99    Closer closer = Closer.create();
100    try {
101      OutputStream out = closer.register(openStream());
102      out.write(bytes);
103      out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330
104    } catch (Throwable e) {
105      throw closer.rethrow(e);
106    } finally {
107      closer.close();
108    }
109  }
110
111  /**
112   * Writes all the bytes from the given {@code InputStream} to this sink. Does not close
113   * {@code input}.
114   *
115   * @throws IOException if an I/O occurs in the process of reading from {@code input} or writing to
116   *     this sink
117   */
118  public long writeFrom(InputStream input) throws IOException {
119    checkNotNull(input);
120
121    Closer closer = Closer.create();
122    try {
123      OutputStream out = closer.register(openStream());
124      long written = ByteStreams.copy(input, out);
125      out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330
126      return written;
127    } catch (Throwable e) {
128      throw closer.rethrow(e);
129    } finally {
130      closer.close();
131    }
132  }
133
134  /**
135   * A char sink that encodes written characters with a charset and writes resulting bytes to this
136   * byte sink.
137   */
138  private final class AsCharSink extends CharSink {
139
140    private final Charset charset;
141
142    private AsCharSink(Charset charset) {
143      this.charset = checkNotNull(charset);
144    }
145
146    @Override
147    public Writer openStream() throws IOException {
148      return new OutputStreamWriter(ByteSink.this.openStream(), charset);
149    }
150
151    @Override
152    public String toString() {
153      return ByteSink.this.toString() + ".asCharSink(" + charset + ")";
154    }
155  }
156}
157