1 7 8 package javax.imageio.stream; 9 10 import java.io.InputStream ; 11 import java.io.IOException ; 12 import java.io.RandomAccessFile ; 13 14 import java.util.ArrayList ; 15 16 29 public class MemoryCacheImageInputStream extends ImageInputStreamImpl { 30 31 private InputStream stream; 32 33 private MemoryCache cache = new MemoryCache (); 34 35 44 public MemoryCacheImageInputStream(InputStream stream) { 45 if (stream == null) { 46 throw new IllegalArgumentException ("stream == null!"); 47 } 48 this.stream = stream; 49 } 50 51 public int read() throws IOException { 52 checkClosed(); 53 bitOffset = 0; 54 long thisByte = streamPos; 55 long pos = cache.loadFromStream(stream, streamPos+1); 56 if (pos >= streamPos+1) { 57 return cache.read(streamPos++); 58 } else { 59 return -1; 60 } 61 } 62 63 public int read(byte[] b, int off, int len) throws IOException { 64 checkClosed(); 65 if (off < 0 || len < 0 || off + len > b.length || off + len < 0) { 67 throw new IndexOutOfBoundsException 68 ("off < 0 || len < 0 || off + len > b.length!"); 69 } 70 71 bitOffset = 0; 72 73 if (len == 0) { 74 return 0; 75 } 76 77 long pos = cache.loadFromStream(stream, streamPos+len); 78 79 len = (int)(pos - streamPos); 81 if (len > 0) { 82 cache.read(b, off, len, streamPos); 83 streamPos += len; 84 return len; 85 } else { 86 return -1; 87 } 88 } 89 90 public void flushBefore(long pos) throws IOException { 91 super.flushBefore(pos); 92 cache.disposeBefore(pos); 93 } 94 95 105 public boolean isCached() { 106 return true; 107 } 108 109 118 public boolean isCachedFile() { 119 return false; 120 } 121 122 131 public boolean isCachedMemory() { 132 return true; 133 } 134 135 139 public void close() throws IOException { 140 super.close(); 141 cache.reset(); 142 stream = null; 143 } 144 145 } 146 | Popular Tags |