01: // ========================================================================
02: // Copyright 1999-2005 Mort Bay Consulting Pty. Ltd.
03: // ------------------------------------------------------------------------
04: // Licensed under the Apache License, Version 2.0 (the "License");
05: // you may not use this file except in compliance with the License.
06: // You may obtain a copy of the License at
07: // http://www.apache.org/licenses/LICENSE-2.0
08: // Unless required by applicable law or agreed to in writing, software
09: // 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: /** 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: * @author Greg Wilkins (gregw)
27: */
28: public class WriterOutputStream extends OutputStream {
29: protected Writer _writer;
30: protected String _encoding;
31: private byte[] _buf = new byte[1];
32:
33: /* ------------------------------------------------------------ */
34: public WriterOutputStream(Writer writer, String encoding) {
35: _writer = writer;
36: _encoding = encoding;
37: }
38:
39: /* ------------------------------------------------------------ */
40: public WriterOutputStream(Writer writer) {
41: _writer = writer;
42: }
43:
44: /* ------------------------------------------------------------ */
45: public void close() throws IOException {
46: _writer.close();
47: _writer = null;
48: _encoding = null;
49: }
50:
51: /* ------------------------------------------------------------ */
52: public void flush() throws IOException {
53: _writer.flush();
54: }
55:
56: /* ------------------------------------------------------------ */
57: public void write(byte[] b) throws IOException {
58: if (_encoding == null)
59: _writer.write(new String(b));
60: else
61: _writer.write(new String(b, _encoding));
62: }
63:
64: /* ------------------------------------------------------------ */
65: public void write(byte[] b, int off, int len) throws IOException {
66: if (_encoding == null)
67: _writer.write(new String(b, off, len));
68: else
69: _writer.write(new String(b, off, len, _encoding));
70: }
71:
72: /* ------------------------------------------------------------ */
73: public synchronized void write(int b) throws IOException {
74: _buf[0] = (byte) b;
75: write(_buf);
76: }
77: }
|