aboutsummaryrefslogtreecommitdiffstats
path: root/guava/src/com/google/common/io/ByteSink.java
blob: 781b2c376b8b3ef22f3b51bea5ec170f2fdb1b35 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
/*
 * Copyright (C) 2012 The Guava Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.common.io;

import static com.google.common.base.Preconditions.checkNotNull;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;

/**
 * A destination to which bytes can be written, such as a file. Unlike an {@link OutputStream}, a
 * {@code ByteSink} is not an open, stateful stream that can be written to and closed. Instead, it
 * is an immutable <i>supplier</i> of {@code OutputStream} instances.
 *
 * <p>{@code ByteSink} provides two kinds of methods:
 * <ul>
 *   <li><b>Methods that return a stream:</b> These methods should return a <i>new</i>, independent
 *   instance each time they are called. The caller is responsible for ensuring that the returned
 *   stream is closed.
 *   <li><b>Convenience methods:</b> These are implementations of common operations that are
 *   typically implemented by opening a stream using one of the methods in the first category, doing
 *   something and finally closing the stream or channel that was opened.
 * </ul>
 *
 * @since 14.0
 * @author Colin Decker
 */
public abstract class ByteSink {

  /**
   * Returns a {@link CharSink} view of this {@code ByteSink} that writes characters to this sink
   * as bytes encoded with the given {@link Charset charset}.
   */
  public CharSink asCharSink(Charset charset) {
    return new AsCharSink(charset);
  }

  /**
   * Opens a new {@link OutputStream} for writing to this sink. This method should return a new,
   * independent stream each time it is called.
   *
   * <p>The caller is responsible for ensuring that the returned stream is closed.
   *
   * @throws IOException if an I/O error occurs in the process of opening the stream
   */
  public abstract OutputStream openStream() throws IOException;

  /**
   * Opens a new {@link BufferedOutputStream} for writing to this sink. This method should return a
   * new, independent stream each time it is called.
   *
   * <p>The caller is responsible for ensuring that the returned stream is closed.
   *
   * @throws IOException if an I/O error occurs in the process of opening the stream
   */
  public BufferedOutputStream openBufferedStream() throws IOException {
    OutputStream out = openStream();
    return (out instanceof BufferedOutputStream)
        ? (BufferedOutputStream) out
        : new BufferedOutputStream(out);
  }

  /**
   * Writes all the given bytes to this sink.
   *
   * @throws IOException if an I/O occurs in the process of writing to this sink
   */
  public void write(byte[] bytes) throws IOException {
    checkNotNull(bytes);

    Closer closer = Closer.create();
    try {
      OutputStream out = closer.register(openStream());
      out.write(bytes);
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }

  /**
   * Writes all the bytes from the given {@code InputStream} to this sink. Does not close
   * {@code input}.
   *
   * @throws IOException if an I/O occurs in the process of reading from {@code input} or writing to
   *     this sink
   */
  public long writeFrom(InputStream input) throws IOException {
    checkNotNull(input);

    Closer closer = Closer.create();
    try {
      OutputStream out = closer.register(openStream());
      return ByteStreams.copy(input, out);
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }

  /**
   * A char sink that encodes written characters with a charset and writes resulting bytes to this
   * byte sink.
   */
  private final class AsCharSink extends CharSink {

    private final Charset charset;

    private AsCharSink(Charset charset) {
      this.charset = checkNotNull(charset);
    }

    @Override
    public Writer openStream() throws IOException {
      return new OutputStreamWriter(ByteSink.this.openStream(), charset);
    }

    @Override
    public String toString() {
      return ByteSink.this.toString() + ".asCharSink(" + charset + ")";
    }
  }
}