1 32 package com.imagero.uio.buffer; 33 34 import com.imagero.uio.io.IOutils; 35 36 import java.io.IOException ; 37 import java.io.InputStream ; 38 39 44 public class InputStreamBufferManager extends AbstractBufferManager { 45 46 InputStream in; 47 48 long sumLength; 49 int bufferCount; 50 51 56 public InputStreamBufferManager(InputStream in) { 57 this(defaultBufferSize, in); 58 } 59 60 66 public InputStreamBufferManager(int bufferSize, InputStream in) { 67 this.bufferSize = bufferSize; 68 this.in = in; 69 } 70 71 78 public byte[] getData(int i) throws IOException { 79 try { 80 return getDataImpl(i); 81 } 82 catch(ArrayIndexOutOfBoundsException ex) { 83 ex.printStackTrace(); 84 throw new IOException (); 85 } 86 } 87 88 97 protected byte[] getDataImpl(int i) throws IOException { 98 if(i >= bufferCount) { 99 fillBuffer(i); 100 } 101 Buffer buffer = accessManager.get(i); 102 if(buffer != null) { 103 return buffer.getData(); 104 } 105 return empty; 106 } 107 108 113 protected void fillBuffer(int tillIndex) { 114 int count = tillIndex - bufferCount + 1; 115 int read = 0; 116 for(int i = 0; i < count; i++) { 117 byte[] data = new byte[bufferSize]; 118 try { 119 read = IOutils.readFully2(in, data); 120 if(read < 0) { 121 break; 122 } 123 else { 124 byte[] data0 = data; 125 if(read != data.length) { 126 data0 = new byte[read]; 127 System.arraycopy(data, 0, data0, 0, read); 128 } 129 Buffer ds0 = new ByteBuffer(data0); 130 accessManager.add(ds0); 131 bufferCount++; 132 sumLength += read; 133 } 134 } 135 catch(IOException ex) { 136 ex.printStackTrace(); 137 break; 138 } 139 } 140 } 141 142 151 public int getDataLength(int i) { 152 return accessManager.getBufferLength(i); 153 } 154 155 162 public int getIndex(long pos) { 163 if(pos < 0) { 164 return -1; 165 } 166 167 return (int) (pos / bufferSize); 168 } 169 170 174 public long getLength() { 175 return sumLength; 176 } 177 178 185 public long getDataStart(int i) { 186 return bufferSize * i; 187 } 188 189 192 public void close() { 193 IOutils.closeStream(in); 194 clear(); 195 } 196 } 197 | Popular Tags |