1 package org.backsource.utils.io;
2
3 import java.io.Reader;
4 import java.io.InputStream;
5 import java.io.IOException;
6
7 /***
8 * <p>An InputStream of of a Reader, which might no allways work.
9 *
10 * <p>Wrap your reader in an input stream. Sometime the API:s you use just don't give you a breake. One only gives you a Reader the other one want's an InputStream. Then you might want to use this class. But I only think it works on iso-8859-1 encoded files.
11 *
12 * Stolen from somewhere?
13 * @version $Revision: 1.1.1.1 $
14 */
15 public class ReaderInputStream extends InputStream {
16 protected Reader rdr;
17 protected String encoding;
18 public ReaderInputStream (Reader rdr) {
19 this.rdr = rdr;
20 }
21 public ReaderInputStream (Reader rdr, String encoding) {
22 this.rdr = rdr;
23 this.encoding = encoding;
24 }
25 protected byte slack [];
26 protected int begin;
27 public synchronized int read () throws IOException {
28 if (rdr == null) throw new IOException("closed");
29 byte result;
30 if (slack != null && begin < slack.length) {
31 result = slack[begin];
32 if (++ begin == slack.length) slack = null;
33 } else {
34 byte buf [] = new byte[1];
35 if (read(buf, 0, 1) <= 0) return -1;
36 result = buf[0];
37 }
38 return result < 0 ? 256 + result : result;
39 }
40 public synchronized int read (byte b [], int off, int len)
41 throws IOException {
42 if (rdr == null) throw new IOException("closed");
43 while (slack == null) {
44 char buf [] = new char[len];
45 int n = rdr.read(buf);
46 if (n == -1) return -1;
47 if (n > 0) {
48 String s = new String(buf, 0, n);
49 slack = encoding == null ? s.getBytes() : s.getBytes(encoding);
50 begin = 0;
51 }
52 }
53 if (len > slack.length-begin) len = slack.length-begin;
54 System.arraycopy(slack, begin, b, off, len);
55 if ((begin += len) >= slack.length) slack = null;
56 return len;
57 }
58 public synchronized int available () throws IOException {
59 if (rdr == null) throw new IOException("closed");
60 if (slack != null) return slack.length-begin;
61 return rdr.ready() ? 1 : 0;
62 }
63 public boolean markSupported () {
64 return false;
65 }
66 public synchronized void reset() throws IOException {
67 if (rdr == null) throw new IOException("closed");
68 slack = null;
69 rdr.reset();
70 }
71 public synchronized void close () throws IOException {
72 rdr.close();
73 slack = null; rdr = null;
74 }
75 }
76