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.BufferedReader;
28 import java.io.ByteArrayInputStream;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.io.InputStreamReader;
32 import java.io.UnsupportedEncodingException;
33
34 /***
35 * Reads text data and makes the lines accessible as records. The records are returned as byte
36 * arrays. Internally, the a Reader is used to perform the translation from characters to bytes.
37 *
38 * @author Lars Behnke
39 */
40 public class TextInputStream extends InputStream implements RecordReadSupport {
41
42 private static final int BUFFER_SIZE = 2048;
43
44 private BufferedReader reader;
45
46 private String outputEncoding;
47
48 private ByteArrayInputStream byteBuffer;
49
50 /***
51 * Constructor.
52 *
53 * @param is The input stream.
54 * @param inputEncoding The encoding.
55 * @throws UnsupportedEncodingException Thrown if encoding is unknown.
56 */
57 public TextInputStream(InputStream is, String inputEncoding) throws UnsupportedEncodingException {
58 this(is, inputEncoding, null);
59 }
60
61 /***
62 * Constructor.
63 *
64 * @param is The input stream.
65 * @param inputEncoding The encoding of the inbound text data.
66 * @param outputEncoding The encoding of the outbound text data.
67 * @throws UnsupportedEncodingException Thrown if encoding is unknown.
68 */
69 public TextInputStream(InputStream is, String inputEncoding, String outputEncoding)
70 throws UnsupportedEncodingException {
71 super();
72 this.reader = new BufferedReader(new InputStreamReader(is, inputEncoding));
73 this.outputEncoding = outputEncoding;
74 }
75
76 /***
77 * {@inheritDoc}
78 */
79 public int read() throws IOException {
80 int result;
81 if (byteBuffer == null) {
82 result = -1;
83 } else {
84 result = byteBuffer.read();
85 }
86 if (result == -1) {
87 char[] chars = new char[BUFFER_SIZE];
88 int charCount = reader.read(chars);
89 if (charCount == -1) {
90 return -1;
91 }
92 String s = new String(chars, 0, charCount);
93 if (outputEncoding == null) {
94 byteBuffer = new ByteArrayInputStream(s.getBytes());
95 } else {
96 byteBuffer = new ByteArrayInputStream(s.getBytes(outputEncoding));
97 }
98 result = read();
99 }
100 return result;
101 }
102
103 /***
104 * {@inheritDoc}
105 */
106 public byte[] readRecord() throws IOException {
107 byte[] result;
108 String line = reader.readLine();
109 if (line == null) {
110 result = null;
111 } else {
112 if (outputEncoding == null) {
113 result = line.getBytes();
114 } else {
115 result = line.getBytes(outputEncoding);
116 }
117 }
118 return result;
119 }
120
121 /***
122 * {@inheritDoc}
123 */
124 public void close() throws IOException {
125 super.close();
126 reader.close();
127 }
128 }