01: /*
02:
03: This software is OSI Certified Open Source Software.
04: OSI Certified is a certification mark of the Open Source Initiative.
05:
06: The license (Mozilla version 1.0) can be read at the MMBase site.
07: See http://www.MMBase.org/license
08:
09: */
10:
11: package org.mmbase.util;
12:
13: import java.io.*;
14:
15: /**
16: * Oddly enough, Java does not provide this itself. It is necessary
17: * though in GenericResponseWrapper, because you sometimes are stuck
18: * with a writer, while an outputStream is requested.
19: * Code inspired by http://www.koders.com/java/fid5A2897DDE860FCC1D9D9E0EA5A2834CC62A87E85.aspx
20: * @author Michiel Meeuwissen
21: * @since MMBase-1.7.4
22: */
23: public class WriterOutputStream extends OutputStream {
24: protected Writer writer;
25: protected String encoding;
26: private byte[] buf = new byte[1];
27:
28: public WriterOutputStream(Writer writer, String encoding) {
29: this .writer = writer;
30: this .encoding = encoding;
31: }
32:
33: public void close() throws IOException {
34: writer.close();
35: writer = null;
36: encoding = null;
37: }
38:
39: public void flush() throws IOException {
40: writer.flush();
41: }
42:
43: public void write(byte[] b) throws IOException {
44: if (encoding == null) {
45: writer.write(new String(b));
46: } else {
47: writer.write(new String(b, encoding));
48: }
49:
50: }
51:
52: public void write(byte[] b, int off, int len) throws IOException {
53: if (encoding == null) {
54: writer.write(new String(b, off, len));
55: } else {
56: writer.write(new String(b, off, len, encoding));
57: }
58: }
59:
60: public synchronized void write(int b) throws IOException {
61: buf[0] = (byte) b;
62: write(buf);
63: }
64: }
|