1
2
3
4
5
6
7
8
9
10
11
12
13 package org.abstracthorizon.danube.http.util;
14
15 import java.io.IOException;
16 import java.io.OutputStream;
17 import java.io.UnsupportedEncodingException;
18 import java.io.Writer;
19 import java.nio.charset.Charset;
20 import java.nio.charset.IllegalCharsetNameException;
21
22
23
24
25
26
27 public class BufferlessOutputStreamWriter extends Writer {
28
29 protected OutputStream stream;
30
31 protected Charset charSet;
32
33 public BufferlessOutputStreamWriter(OutputStream stream) {
34 this.stream = stream;
35 }
36
37 public BufferlessOutputStreamWriter(OutputStream stream, String encoding) throws UnsupportedEncodingException, IllegalCharsetNameException {
38 this.stream = stream;
39 setEncoding(encoding);
40 }
41
42 public void setEncoding(String encoding) throws UnsupportedEncodingException, IllegalCharsetNameException {
43
44 if (encoding != null) {
45 if ((charSet == null) || !encoding.equals(charSet.name())) {
46 charSet = Charset.forName(encoding);
47 }
48 } else {
49 encoding = null;
50 }
51 }
52
53 public String getEncoding() {
54 if (charSet != null) {
55 return charSet.name();
56 } else {
57 return null;
58 }
59 }
60
61 @Override
62 public void close() throws IOException {
63 stream.close();
64 }
65
66 @Override
67 public void flush() throws IOException {
68 stream.close();
69 }
70
71 @Override
72 public void write(char[] cbuf, int off, int len) throws IOException {
73 String s = new String(cbuf, off, len);
74 if (charSet == null) {
75 stream.write(s.getBytes());
76 } else {
77 stream.write(charSet.encode(s).array());
78 }
79 }
80
81
82 }