01: /*
02: * Copyright 2004-2008 H2 Group. Licensed under the H2 License, Version 1.0
03: * (http://h2database.com/html/license.html).
04: * Initial Developer: H2 Group
05: */
06: package org.h2.util;
07:
08: import java.io.BufferedWriter;
09: import java.io.ByteArrayOutputStream;
10: import java.io.IOException;
11: import java.io.InputStream;
12: import java.io.OutputStreamWriter;
13: import java.io.Reader;
14: import java.io.UnsupportedEncodingException;
15: import java.io.Writer;
16: import java.sql.SQLException;
17:
18: import org.h2.engine.Constants;
19: import org.h2.message.Message;
20:
21: /**
22: * The reader input stream wraps a reader and convert the character to the UTF-8
23: * format.
24: */
25: public class ReaderInputStream extends InputStream {
26:
27: private final Reader reader;
28: private final char[] chars;
29: private final ByteArrayOutputStream out;
30: private final Writer writer;
31: private int pos;
32: private int remaining;
33: private byte[] buffer;
34:
35: public ReaderInputStream(Reader reader) throws SQLException {
36: chars = new char[Constants.IO_BUFFER_SIZE];
37: this .reader = reader;
38: out = new ByteArrayOutputStream(Constants.IO_BUFFER_SIZE);
39: try {
40: writer = new BufferedWriter(new OutputStreamWriter(out,
41: Constants.UTF8));
42: } catch (UnsupportedEncodingException e) {
43: throw Message.convert(e);
44: }
45: }
46:
47: private void fillBuffer() throws IOException {
48: if (remaining == 0) {
49: pos = 0;
50: remaining = reader.read(chars, 0, Constants.IO_BUFFER_SIZE);
51: if (remaining < 0) {
52: return;
53: }
54: writer.write(chars, 0, remaining);
55: writer.flush();
56: buffer = out.toByteArray();
57: remaining = buffer.length;
58: out.reset();
59: }
60: }
61:
62: public int read() throws IOException {
63: if (remaining == 0) {
64: fillBuffer();
65: }
66: if (remaining < 0) {
67: return -1;
68: }
69: remaining--;
70: return buffer[pos++] & 0xff;
71: }
72:
73: }
|