1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 package net.sf.hermesftp.streams;
26
27 import java.io.ByteArrayOutputStream;
28 import java.io.IOException;
29 import java.io.OutputStream;
30 import java.io.OutputStreamWriter;
31 import java.io.UnsupportedEncodingException;
32
33 /***
34 * Returns text data as byte arrays. In contrast to WriterOutputStream this class supports records.
35 * Internally, the a Writer is used to perform the translation from characters to bytes.
36 *
37 * @author Lars Behnke
38 */
39 public class TextOutputStream extends OutputStream implements RecordWriteSupport {
40
41 private OutputStream os;
42
43 private ByteArrayOutputStream byteBuffer;
44
45 private OutputStreamWriter writer;
46
47 private String inputEncoding;
48
49 private String outputEncoding;
50
51 /***
52 * Constructor.
53 *
54 * @param os The output stream.
55 * @param outputEncoding The encoding of outbound text data.
56 * @throws UnsupportedEncodingException Thrown if encoding is unknown.
57 */
58 public TextOutputStream(OutputStream os, String outputEncoding) throws UnsupportedEncodingException {
59 this(os, outputEncoding, null);
60 }
61
62 /***
63 * Constructor.
64 *
65 * @param os The output stream.
66 * @param outputEncoding The encoding of outbound text data.
67 * @param inputEncoding The encoding of inbound text data.
68 * @throws UnsupportedEncodingException Thrown if encoding is unknown.
69 */
70 public TextOutputStream(OutputStream os, String outputEncoding, String inputEncoding)
71 throws UnsupportedEncodingException {
72 super();
73
74 this.os = os;
75 this.byteBuffer = new ByteArrayOutputStream();
76 this.writer = new OutputStreamWriter(os, outputEncoding);
77 this.inputEncoding = inputEncoding;
78 this.outputEncoding = outputEncoding;
79 }
80
81 /***
82 * {@inheritDoc}
83 */
84 public void write(int b) throws IOException {
85 byteBuffer.write(b);
86 }
87
88 /***
89 * {@inheritDoc}
90 */
91 public void writeRecord(byte[] data, boolean eof) throws IOException {
92 String line;
93 if (inputEncoding != null) {
94 line = new String(data, inputEncoding);
95 } else {
96 line = new String(data);
97 }
98
99 if (os instanceof RecordWriteSupport) {
100 ((RecordWriteSupport) os).writeRecord(line.getBytes(outputEncoding), eof);
101 } else {
102 writer.write(line + System.getProperty("line.separator"));
103 }
104
105 }
106
107 /***
108 * {@inheritDoc}
109 */
110 public void flush() throws IOException {
111 byte[] data = byteBuffer.toByteArray();
112 String s;
113 if (inputEncoding != null) {
114 s = new String(data, inputEncoding);
115 } else {
116 s = new String(data);
117 }
118 writer.write(s);
119 writer.flush();
120 byteBuffer.reset();
121 }
122
123 /***
124 * {@inheritDoc}
125 */
126 public void close() throws IOException {
127 flush();
128 byteBuffer.close();
129 writer.close();
130 }
131
132 }