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