1 36 package com.ibatis.common.io; 37 38 import java.io.*; 39 40 43 public class ReaderInputStream extends InputStream { 44 protected Reader reader; 45 protected ByteArrayOutputStream byteArrayOut; 46 protected Writer writer; 47 protected char[] chars; 48 protected byte[] buffer; 49 protected int index, length; 50 51 56 public ReaderInputStream(Reader reader) { 57 this.reader = reader; 58 byteArrayOut = new ByteArrayOutputStream(); 59 writer = new OutputStreamWriter(byteArrayOut); 60 chars = new char[1024]; 61 } 62 63 70 public ReaderInputStream(Reader reader, String encoding) throws UnsupportedEncodingException { 71 this.reader = reader; 72 byteArrayOut = new ByteArrayOutputStream(); 73 writer = new OutputStreamWriter(byteArrayOut, encoding); 74 chars = new char[1024]; 75 } 76 77 80 public int read() throws IOException { 81 if (index >= length) 82 fillBuffer(); 83 if (index >= length) 84 return -1; 85 return 0xff & buffer[index++]; 86 } 87 88 protected void fillBuffer() throws IOException { 89 if (length < 0) 90 return; 91 int numChars = reader.read(chars); 92 if (numChars < 0) { 93 length = -1; 94 } else { 95 byteArrayOut.reset(); 96 writer.write(chars, 0, numChars); 97 writer.flush(); 98 buffer = byteArrayOut.toByteArray(); 99 length = buffer.length; 100 index = 0; 101 } 102 } 103 104 107 public int read(byte[] data, int off, int len) throws IOException { 108 if (index >= length) 109 fillBuffer(); 110 if (index >= length) 111 return -1; 112 int amount = Math.min(len, length - index); 113 System.arraycopy(buffer, index, data, off, amount); 114 index += amount; 115 return amount; 116 } 117 118 121 public int available() throws IOException { 122 return (index < length) ? length - index : 123 ((length >= 0) && reader.ready()) ? 1 : 0; 124 } 125 126 129 public void close() throws IOException { 130 reader.close(); 131 } 132 } 133 | Popular Tags |