1 // ======================================================================== 2 // Copyright (c) 1999-2009 Mort Bay Consulting Pty. Ltd. 3 // ------------------------------------------------------------------------ 4 // All rights reserved. This program and the accompanying materials 5 // are made available under the terms of the Eclipse Public License v1.0 6 // and Apache License v2.0 which accompanies this distribution. 7 // The Eclipse Public License is available at 8 // http://www.eclipse.org/legal/epl-v10.html 9 // The Apache License v2.0 is available at 10 // http://www.opensource.org/licenses/apache2.0.php 11 // You may elect to redistribute this code under either of these licenses. 12 // ======================================================================== 13 14 package org.eclipse.jetty.io; 15 16 import java.io.IOException; 17 import java.io.OutputStream; 18 import java.io.Writer; 19 20 21 /* ------------------------------------------------------------ */ 22 /** Wrap a Writer as an OutputStream. 23 * When all you have is a Writer and only an OutputStream will do. 24 * Try not to use this as it indicates that your design is a dogs 25 * breakfast (JSP made me write it). 26 * 27 */ 28 public class WriterOutputStream extends OutputStream 29 { 30 protected final Writer _writer; 31 protected final String _encoding; 32 private final byte[] _buf=new byte[1]; 33 34 /* ------------------------------------------------------------ */ 35 public WriterOutputStream(Writer writer, String encoding) 36 { 37 _writer=writer; 38 _encoding=encoding; 39 } 40 41 /* ------------------------------------------------------------ */ 42 public WriterOutputStream(Writer writer) 43 { 44 _writer=writer; 45 _encoding=null; 46 } 47 48 /* ------------------------------------------------------------ */ 49 public void close() 50 throws IOException 51 { 52 _writer.close(); 53 } 54 55 /* ------------------------------------------------------------ */ 56 public void flush() 57 throws IOException 58 { 59 _writer.flush(); 60 } 61 62 /* ------------------------------------------------------------ */ 63 public void write(byte[] b) 64 throws IOException 65 { 66 if (_encoding==null) 67 _writer.write(new String(b)); 68 else 69 _writer.write(new String(b,_encoding)); 70 } 71 72 /* ------------------------------------------------------------ */ 73 public void write(byte[] b, int off, int len) 74 throws IOException 75 { 76 if (_encoding==null) 77 _writer.write(new String(b,off,len)); 78 else 79 _writer.write(new String(b,off,len,_encoding)); 80 } 81 82 /* ------------------------------------------------------------ */ 83 public synchronized void write(int b) 84 throws IOException 85 { 86 _buf[0]=(byte)b; 87 write(_buf); 88 } 89 } 90