1 // ======================================================================== 2 // Copyright 1999-2005 Mort Bay Consulting Pty. Ltd. 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 // http://www.apache.org/licenses/LICENSE-2.0 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 // ======================================================================== 14 15 package org.mortbay.io; 16 17 import java.io.IOException; 18 import java.io.OutputStream; 19 import java.io.Writer; 20 21 22 /* ------------------------------------------------------------ */ 23 /** Wrap a Writer as an OutputStream. 24 * When all you have is a Writer and only an OutputStream will do. 25 * Try not to use this as it indicates that your design is a dogs 26 * breakfast (JSP made me write it). 27 * @author Greg Wilkins (gregw) 28 */ 29 public class WriterOutputStream extends OutputStream 30 { 31 protected Writer _writer; 32 protected String _encoding; 33 private byte[] _buf=new byte[1]; 34 35 /* ------------------------------------------------------------ */ 36 public WriterOutputStream(Writer writer, String encoding) 37 { 38 _writer=writer; 39 _encoding=encoding; 40 } 41 42 /* ------------------------------------------------------------ */ 43 public WriterOutputStream(Writer writer) 44 { 45 _writer=writer; 46 } 47 48 /* ------------------------------------------------------------ */ 49 public void close() 50 throws IOException 51 { 52 _writer.close(); 53 _writer=null; 54 _encoding=null; 55 } 56 57 /* ------------------------------------------------------------ */ 58 public void flush() 59 throws IOException 60 { 61 _writer.flush(); 62 } 63 64 /* ------------------------------------------------------------ */ 65 public void write(byte[] b) 66 throws IOException 67 { 68 if (_encoding==null) 69 _writer.write(new String(b)); 70 else 71 _writer.write(new String(b,_encoding)); 72 } 73 74 /* ------------------------------------------------------------ */ 75 public void write(byte[] b, int off, int len) 76 throws IOException 77 { 78 if (_encoding==null) 79 _writer.write(new String(b,off,len)); 80 else 81 _writer.write(new String(b,off,len,_encoding)); 82 } 83 84 /* ------------------------------------------------------------ */ 85 public synchronized void write(int b) 86 throws IOException 87 { 88 _buf[0]=(byte)b; 89 write(_buf); 90 } 91 } 92