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 17 package com.google.common.io; 18 19 import static com.google.common.base.Charsets.UTF_8; 20 21 import java.io.FilterWriter; 22 import java.io.IOException; 23 import java.io.OutputStreamWriter; 24 import java.io.Writer; 25 26 /** 27 * A char sink for testing that has configurable behavior. 28 * 29 * @author Colin Decker 30 */ 31 public class TestCharSink extends CharSink implements TestStreamSupplier { 32 33 private final TestByteSink byteSink; 34 TestCharSink(TestOption... options)35 public TestCharSink(TestOption... options) { 36 this.byteSink = new TestByteSink(options); 37 } 38 getString()39 public String getString() { 40 return new String(byteSink.getBytes(), UTF_8); 41 } 42 43 @Override wasStreamOpened()44 public boolean wasStreamOpened() { 45 return byteSink.wasStreamOpened(); 46 } 47 48 @Override wasStreamClosed()49 public boolean wasStreamClosed() { 50 return byteSink.wasStreamClosed(); 51 } 52 53 @Override openStream()54 public Writer openStream() throws IOException { 55 // using TestByteSink's output stream to get option behavior, so flush to it on every write 56 return new FilterWriter(new OutputStreamWriter(byteSink.openStream(), UTF_8)) { 57 @Override 58 public void write(int c) throws IOException { 59 super.write(c); 60 flush(); 61 } 62 63 @Override 64 public void write(char[] cbuf, int off, int len) throws IOException { 65 super.write(cbuf, off, len); 66 flush(); 67 } 68 69 @Override 70 public void write(String str, int off, int len) throws IOException { 71 super.write(str, off, len); 72 flush(); 73 } 74 }; 75 } 76 } 77