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.RandomAccessFile ; 38 39 44 public class RAFBufferManager extends AbstractBufferManager { 45 46 protected RandomAccessFile raf; 47 48 Integer maxKey = new Integer (0); 49 50 51 public RAFBufferManager(RandomAccessFile raf) throws IOException { 52 this(raf, 0); 53 } 54 55 public RAFBufferManager(RandomAccessFile raf, long offset) throws IOException { 56 this(raf, offset, raf.length()); 57 } 58 59 64 public RAFBufferManager(RandomAccessFile raf, long offset, long length) { 65 this(raf, offset, length, defaultBufferSize); 66 } 67 68 75 public RAFBufferManager(RandomAccessFile raf, long offset, long length, int dsLength) { 76 this.bufferSize = dsLength; 77 this.raf = raf; 78 this.offset = offset; 79 this.length = length; 80 81 Buffer buffer = createBuffer(raf, offset, dsLength); 82 accessManager.put(new Integer (0), buffer); 83 } 84 85 protected Buffer createBuffer(RandomAccessFile raf, long offset, int dsLength) { 86 long maxLength = 0; 87 try { 88 maxLength = raf.length() - offset; 89 } 90 catch (IOException ex) { 91 ex.printStackTrace(); 92 } 93 if(maxLength < 0) { 94 return new RAFBufferRO(raf, offset, 0); 95 } 96 return new RAFBufferRO(raf, offset, (int) Math.min(maxLength, dsLength)); 97 } 98 99 108 public byte[] getData(int i) throws IOException { 109 try { 110 return getDataImpl(i); 111 } catch (ArrayIndexOutOfBoundsException ex) { 112 throw ex; 113 } 114 } 115 116 125 protected byte[] getDataImpl(int i) throws IOException { 126 Integer key = new Integer (i); 127 Buffer uds = (accessManager.get(key)); 128 if (uds == null) { 129 uds = createBuffer(raf, offset + bufferSize * i, bufferSize); 130 if(uds == null) { 131 return null; 132 } 133 accessManager.put(key, uds); 134 if (key.intValue() > maxKey.intValue()) { 135 maxKey = key; 136 } 137 } 138 return uds.getData(); 139 } 140 141 148 public int getDataLength(int i) { 149 return bufferSize; 150 } 151 152 159 public int getIndex(long pos) { 160 if (pos < 0) { 161 return -1; 162 } 163 return (int) (pos / bufferSize); 164 } 165 166 169 public long getLength() { 170 return (int) length; 171 } 172 173 179 public long getDataStart(int i) { 180 return bufferSize * i; 184 } 185 186 public void close() { 187 IOutils.closeStream(raf); 188 clear(); 189 } 190 191 public void clear() { 192 accessManager.clear(); 193 maxKey = new Integer (0); 194 } 195 } 196 | Popular Tags |