1 /* Copyright 2004 The Apache Software Foundation
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.xmlbeans.impl.common;
17
18 import java.io.Reader;
19 import java.io.OutputStreamWriter;
20 import java.io.Writer;
21 import java.io.UnsupportedEncodingException;
22 import java.io.IOException;
23
24 public class ReaderInputStream extends PushedInputStream
25 {
26 private Reader reader;
27 private Writer writer;
28 private char[] buf;
29 public static int defaultBufferSize = 2048;
30
31 public ReaderInputStream(Reader reader, String encoding) throws UnsupportedEncodingException
32 {
33 this(reader, encoding, defaultBufferSize);
34 }
35
36 public ReaderInputStream(Reader reader, String encoding, int bufferSize) throws UnsupportedEncodingException
37 {
38 if (bufferSize <= 0)
39 throw new IllegalArgumentException("Buffer size <= 0");
40
41 this.reader = reader;
42 this.writer = new OutputStreamWriter(getOutputStream(), encoding);
43 buf = new char[bufferSize];
44 }
45
46 public void fill(int requestedBytes) throws IOException
47 {
48 do
49 {
50 int chars = reader.read(buf);
51 if (chars < 0)
52 return;
53
54 writer.write(buf, 0, chars);
55 writer.flush();
56 }
57 while (available() <= 0); // loop for safety, in case encoding didn't produce any bytes yet
58 }
59 }