1 5 package org.h2.util; 6 7 import java.io.ByteArrayOutputStream ; 8 import java.io.IOException ; 9 import java.io.InputStream ; 10 import java.io.OutputStreamWriter ; 11 import java.io.Reader ; 12 import java.io.UnsupportedEncodingException ; 13 import java.sql.SQLException ; 14 15 import org.h2.engine.Constants; 16 import org.h2.message.Message; 17 18 21 22 public class ReaderInputStream extends InputStream { 23 24 private Reader reader; 25 private int pos; 26 private int remaining; 27 private char[] chars; 28 private byte[] buffer; 29 private ByteArrayOutputStream out; 30 private OutputStreamWriter writer; 31 32 public ReaderInputStream(Reader reader) throws SQLException { 33 chars = new char[Constants.IO_BUFFER_SIZE]; 34 this.reader = reader; 35 out = new ByteArrayOutputStream (Constants.IO_BUFFER_SIZE); 36 try { 37 writer = new OutputStreamWriter (out, Constants.UTF8); 38 } catch (UnsupportedEncodingException e) { 39 throw Message.convert(e); 40 } 41 } 42 43 private void fillBuffer() throws IOException { 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 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 { 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 |