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.Beta; 020import com.google.common.annotations.GwtIncompatible; 021import com.google.errorprone.annotations.CanIgnoreReturnValue; 022import java.io.BufferedWriter; 023import java.io.IOException; 024import java.io.Reader; 025import java.io.Writer; 026import java.nio.charset.Charset; 027import java.util.Iterator; 028import java.util.stream.Stream; 029 030/** 031 * A destination to which characters can be written, such as a text file. Unlike a {@link Writer}, a 032 * {@code CharSink} is not an open, stateful stream that can be written to and closed. Instead, it 033 * is an immutable <i>supplier</i> of {@code Writer} instances. 034 * 035 * <p>{@code CharSink} provides two kinds of methods: 036 * 037 * <ul> 038 * <li><b>Methods that return a writer:</b> These methods should return a <i>new</i>, independent 039 * instance each time they are called. The caller is responsible for ensuring that the 040 * returned writer is closed. 041 * <li><b>Convenience methods:</b> These are implementations of common operations that are 042 * typically implemented by opening a writer using one of the methods in the first category, 043 * doing something and finally closing the writer that was opened. 044 * </ul> 045 * 046 * <p>Any {@link ByteSink} may be viewed as a {@code CharSink} with a specific {@linkplain Charset 047 * character encoding} using {@link ByteSink#asCharSink(Charset)}. Characters written to the 048 * resulting {@code CharSink} will written to the {@code ByteSink} as encoded bytes. 049 * 050 * @since 14.0 051 * @author Colin Decker 052 */ 053@GwtIncompatible 054public abstract class CharSink { 055 056 /** Constructor for use by subclasses. */ 057 protected CharSink() {} 058 059 /** 060 * Opens a new {@link Writer} for writing to this sink. This method returns a new, independent 061 * writer each time it is called. 062 * 063 * <p>The caller is responsible for ensuring that the returned writer is closed. 064 * 065 * @throws IOException if an I/O error occurs while opening the writer 066 */ 067 public abstract Writer openStream() throws IOException; 068 069 /** 070 * Opens a new buffered {@link Writer} for writing to this sink. The returned stream is not 071 * required to be a {@link BufferedWriter} in order to allow implementations to simply delegate to 072 * {@link #openStream()} when the stream returned by that method does not benefit from additional 073 * buffering. This method returns a new, independent writer each time it is called. 074 * 075 * <p>The caller is responsible for ensuring that the returned writer is closed. 076 * 077 * @throws IOException if an I/O error occurs while opening the writer 078 * @since 15.0 (in 14.0 with return type {@link BufferedWriter}) 079 */ 080 public Writer openBufferedStream() throws IOException { 081 Writer writer = openStream(); 082 return (writer instanceof BufferedWriter) 083 ? (BufferedWriter) writer 084 : new BufferedWriter(writer); 085 } 086 087 /** 088 * Writes the given character sequence to this sink. 089 * 090 * @throws IOException if an I/O error while writing to this sink 091 */ 092 public void write(CharSequence charSequence) throws IOException { 093 checkNotNull(charSequence); 094 095 Closer closer = Closer.create(); 096 try { 097 Writer out = closer.register(openStream()); 098 out.append(charSequence); 099 out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330 100 } catch (Throwable e) { 101 throw closer.rethrow(e); 102 } finally { 103 closer.close(); 104 } 105 } 106 107 /** 108 * Writes the given lines of text to this sink with each line (including the last) terminated with 109 * the operating system's default line separator. This method is equivalent to {@code 110 * writeLines(lines, System.getProperty("line.separator"))}. 111 * 112 * @throws IOException if an I/O error occurs while writing to this sink 113 */ 114 public void writeLines(Iterable<? extends CharSequence> lines) throws IOException { 115 writeLines(lines, System.getProperty("line.separator")); 116 } 117 118 /** 119 * Writes the given lines of text to this sink with each line (including the last) terminated with 120 * the given line separator. 121 * 122 * @throws IOException if an I/O error occurs while writing to this sink 123 */ 124 public void writeLines(Iterable<? extends CharSequence> lines, String lineSeparator) 125 throws IOException { 126 writeLines(lines.iterator(), lineSeparator); 127 } 128 129 /** 130 * Writes the given lines of text to this sink with each line (including the last) terminated with 131 * the operating system's default line separator. This method is equivalent to {@code 132 * writeLines(lines, System.getProperty("line.separator"))}. 133 * 134 * @throws IOException if an I/O error occurs while writing to this sink 135 * @since 22.0 136 */ 137 @Beta 138 public void writeLines(Stream<? extends CharSequence> lines) throws IOException { 139 writeLines(lines, System.getProperty("line.separator")); 140 } 141 142 /** 143 * Writes the given lines of text to this sink with each line (including the last) terminated with 144 * the given line separator. 145 * 146 * @throws IOException if an I/O error occurs while writing to this sink 147 * @since 22.0 148 */ 149 @Beta 150 public void writeLines(Stream<? extends CharSequence> lines, String lineSeparator) 151 throws IOException { 152 writeLines(lines.iterator(), lineSeparator); 153 } 154 155 private void writeLines(Iterator<? extends CharSequence> lines, String lineSeparator) 156 throws IOException { 157 checkNotNull(lineSeparator); 158 159 try (Writer out = openBufferedStream()) { 160 while (lines.hasNext()) { 161 out.append(lines.next()).append(lineSeparator); 162 } 163 } 164 } 165 166 /** 167 * Writes all the text from the given {@link Readable} (such as a {@link Reader}) to this sink. 168 * Does not close {@code readable} if it is {@code Closeable}. 169 * 170 * @return the number of characters written 171 * @throws IOException if an I/O error occurs while reading from {@code readable} or writing to 172 * this sink 173 */ 174 @CanIgnoreReturnValue 175 public long writeFrom(Readable readable) throws IOException { 176 checkNotNull(readable); 177 178 Closer closer = Closer.create(); 179 try { 180 Writer out = closer.register(openStream()); 181 long written = CharStreams.copy(readable, out); 182 out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330 183 return written; 184 } catch (Throwable e) { 185 throw closer.rethrow(e); 186 } finally { 187 closer.close(); 188 } 189 } 190}