1 package hudson.util; 2 3 import java.io.IOException ; 4 import java.io.OutputStream ; 5 import java.io.Writer ; 6 import java.nio.ByteBuffer ; 7 import java.nio.CharBuffer ; 8 import java.nio.charset.Charset ; 9 import java.nio.charset.CharsetDecoder ; 10 import java.nio.charset.CoderResult ; 11 import java.nio.charset.UnsupportedCharsetException ; 12 13 19 public class WriterOutputStream extends OutputStream { 20 private final Writer writer; 21 private final CharsetDecoder decoder; 22 23 private ByteBuffer buf = ByteBuffer.allocate(1024); 24 private CharBuffer out = CharBuffer.allocate(1024); 25 26 public WriterOutputStream(Writer out) { 27 this.writer = out; 28 decoder = DEFAULT_CHARSET.newDecoder(); 29 } 30 31 public void write(int b) throws IOException { 32 if(buf.remaining()==0) 33 decode(false); 34 buf.put((byte)b); 35 } 36 37 public void write(byte b[], int off, int len) throws IOException { 38 while(len>0) { 39 if(buf.remaining()==0) 40 decode(false); 41 int sz = Math.min(buf.remaining(),len); 42 buf.put(b,off,sz); 43 off += sz; 44 len -= sz; 45 } 46 } 47 48 public void flush() throws IOException { 49 decode(false); 50 flushOutput(); 51 writer.flush(); 52 } 53 54 private void flushOutput() throws IOException { 55 writer.write(out.array(),0,out.position()); 56 out.clear(); 57 } 58 59 public void close() throws IOException { 60 decode(true); 61 flushOutput(); 62 writer.close(); 63 64 buf.rewind(); 65 } 66 67 78 private void decode(boolean last) throws IOException { 79 buf.flip(); 80 while(true) { 81 CoderResult r = decoder.decode(buf, out, last); 82 if(r==CoderResult.OVERFLOW) { 83 flushOutput(); 84 continue; 85 } 86 if(r==CoderResult.UNDERFLOW) { 87 buf.compact(); 88 return; 89 } 90 r.throwException(); 92 } 93 } 94 95 private static final Charset DEFAULT_CHARSET = getDefaultCharset(); 96 97 private static Charset getDefaultCharset() { 98 try { 99 String encoding = System.getProperty("file.encoding"); 100 return Charset.forName(encoding); 101 } catch (UnsupportedCharsetException e) { 102 return Charset.forName("UTF-8"); 103 } 104 } 105 } 106 | Popular Tags |