@Override public Writer openStream() throws IOException { return new OutputStreamWriter(ByteSink.this.openStream(), charset); }
/** * Opens a new buffered {@link OutputStream} for writing to this sink. The returned stream is not * required to be a {@link BufferedOutputStream} in order to allow implementations to simply * delegate to {@link #openStream()} when the stream returned by that method does not benefit from * additional buffering (for example, a {@code ByteArrayOutputStream}). This method returns 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 while opening the stream * @since 15.0 (in 14.0 with return type {@link BufferedOutputStream}) */ public OutputStream 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 while 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); out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330 } 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}. * * @return the number of bytes written * @throws IOException if an I/O occurs while reading from {@code input} or writing to this sink */ @CanIgnoreReturnValue public long writeFrom(InputStream input) throws IOException { checkNotNull(input); Closer closer = Closer.create(); try { OutputStream out = closer.register(openStream()); long written = ByteStreams.copy(input, out); out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330 return written; } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } }
/** * Copies the contents of this byte source to the given {@code ByteSink}. * * @return the number of bytes copied * @throws IOException if an I/O error occurs while reading from this source or writing to * {@code sink} */ @CanIgnoreReturnValue public long copyTo(ByteSink sink) throws IOException { checkNotNull(sink); Closer closer = Closer.create(); try { InputStream in = closer.register(openStream()); OutputStream out = closer.register(sink.openStream()); return ByteStreams.copy(in, out); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } }