1 19 package org.openide.util.io; 20 21 import java.io.*; 22 23 24 30 public class ReaderInputStream extends InputStream { 31 32 private Reader reader; 33 private PipedOutputStream pos; 34 private PipedInputStream pis; 35 private OutputStreamWriter osw; 36 37 41 public ReaderInputStream(Reader reader) throws IOException { 42 this.reader = reader; 43 pos = new PipedOutputStream(); 44 pis = new PipedInputStream(pos); 45 osw = new OutputStreamWriter(pos); 46 } 47 48 52 public ReaderInputStream(Reader reader, String encoding) 53 throws IOException { 54 this.reader = reader; 55 pos = new PipedOutputStream(); 56 pis = new PipedInputStream(pos); 57 osw = new OutputStreamWriter(pos, encoding); 58 } 59 60 public int read() throws IOException { 61 if (pis.available() > 0) { 62 return pis.read(); 63 } 64 65 int c = reader.read(); 66 67 if (c == -1) { 68 return c; 69 } 70 71 osw.write(c); 72 osw.flush(); 73 pos.flush(); 74 75 return pis.read(); 76 } 77 78 public int read(byte[] b, int off, int len) throws IOException { 79 int c = read(); 80 81 if (c == -1) { 82 return -1; 83 } 84 85 b[off] = (byte) c; 86 87 int i = 1; 88 89 for (; (i < len) && reader.ready(); i++) { 91 c = read(); 92 93 if (c == -1) { 94 return i; 95 } 96 97 b[off + i] = (byte) c; 98 } 99 100 return i; 101 } 102 103 public int available() throws IOException { 104 int i = pis.available(); 105 106 if (i > 0) { 107 return i; 108 } 109 110 if (reader.ready()) { 111 return 1; 113 } else { 114 return 0; 115 } 116 } 117 118 public void close() throws IOException { 119 reader.close(); 120 osw.close(); 121 pis.close(); 122 } 123 } 124 | Popular Tags |