KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > h2 > util > ReaderInputStream


1 /*
2  * Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
3  * Initial Developer: H2 Group
4  */

5 package org.h2.util;
6
7 import java.io.ByteArrayOutputStream JavaDoc;
8 import java.io.IOException JavaDoc;
9 import java.io.InputStream JavaDoc;
10 import java.io.OutputStreamWriter JavaDoc;
11 import java.io.Reader JavaDoc;
12 import java.io.UnsupportedEncodingException JavaDoc;
13 import java.sql.SQLException JavaDoc;
14
15 import org.h2.engine.Constants;
16 import org.h2.message.Message;
17
18 /**
19  * @author Thomas
20  */

21
22 public class ReaderInputStream extends InputStream JavaDoc {
23     
24     private Reader JavaDoc reader;
25     private int pos;
26     private int remaining;
27     private char[] chars;
28     private byte[] buffer;
29     private ByteArrayOutputStream JavaDoc out;
30     private OutputStreamWriter JavaDoc writer;
31     
32     public ReaderInputStream(Reader JavaDoc reader) throws SQLException JavaDoc {
33         chars = new char[Constants.IO_BUFFER_SIZE];
34         this.reader = reader;
35         out = new ByteArrayOutputStream JavaDoc(Constants.IO_BUFFER_SIZE);
36         try {
37             writer = new OutputStreamWriter JavaDoc(out, Constants.UTF8);
38         } catch (UnsupportedEncodingException JavaDoc e) {
39             throw Message.convert(e);
40         }
41     }
42     
43     private void fillBuffer() throws IOException JavaDoc {
44         if(remaining == 0) {
45             pos = 0;
46             remaining = reader.read(chars, 0, Constants.IO_BUFFER_SIZE);
47             if(remaining < 0) {
48                 return;
49             }
50 // String s = new String(chars, 0, remaining);
51
// try {
52
// buffer = StringUtils.asBytes(s);
53
// } catch(SQLException e) {
54
// throw new IOException(e.toString());
55
// }
56
writer.write(chars, 0, remaining);
57             writer.flush();
58             buffer = out.toByteArray();
59             remaining = buffer.length;
60             out.reset();
61         }
62     }
63
64     public int read() throws IOException JavaDoc {
65         if(remaining == 0) {
66             fillBuffer();
67         }
68         if(remaining < 0) {
69             return -1;
70         }
71         remaining--;
72         return buffer[pos++] & 0xff;
73     }
74
75 }
76
Popular Tags