1 7 8 package javax.imageio.stream; 9 10 import java.io.DataInput ; 11 import java.io.File ; 12 import java.io.InputStream ; 13 import java.io.IOException ; 14 import java.io.RandomAccessFile ; 15 import com.sun.imageio.stream.StreamCloser; 16 17 24 public class FileCacheImageInputStream extends ImageInputStreamImpl { 25 26 private InputStream stream; 27 28 private File cacheFile; 29 30 private RandomAccessFile cache; 31 32 private static final int BUFFER_LENGTH = 1024; 33 34 private byte[] buf = new byte[BUFFER_LENGTH]; 35 36 private long length = 0L; 37 38 private boolean foundEOF = false; 39 40 62 public FileCacheImageInputStream(InputStream stream, File cacheDir) 63 throws IOException { 64 if (stream == null) { 65 throw new IllegalArgumentException ("stream == null!"); 66 } 67 if ((cacheDir != null) && !(cacheDir.isDirectory())) { 68 throw new IllegalArgumentException ("Not a directory!"); 69 } 70 this.stream = stream; 71 this.cacheFile = 72 File.createTempFile("imageio", ".tmp", cacheDir); 73 this.cache = new RandomAccessFile (cacheFile, "rw"); 74 StreamCloser.addToQueue(this); 75 } 76 77 83 private long readUntil(long pos) throws IOException { 84 if (pos < length) { 86 return pos; 87 } 88 if (foundEOF) { 90 return length; 91 } 92 93 long len = pos - length; 94 cache.seek(length); 95 while (len > 0) { 96 int nbytes = 99 stream.read(buf, 0, (int)Math.min(len, (long)BUFFER_LENGTH)); 100 if (nbytes == -1) { 101 foundEOF = true; 102 return length; 103 } 104 105 cache.write(buf, 0, nbytes); 106 len -= nbytes; 107 length += nbytes; 108 } 109 110 return pos; 111 } 112 113 public int read() throws IOException { 114 bitOffset = 0; 115 long next = streamPos + 1; 116 long pos = readUntil(next); 117 if (pos >= next) { 118 cache.seek(streamPos++); 119 return cache.read(); 120 } else { 121 return -1; 122 } 123 } 124 125 public int read(byte[] b, int off, int len) throws IOException { 126 if (b == null) { 127 throw new NullPointerException (); 128 } 129 if (off < 0 || len < 0 || off + len > b.length || off + len < 0) { 131 throw new IndexOutOfBoundsException (); 132 } 133 if (len == 0) { 134 return 0; 135 } 136 137 checkClosed(); 138 139 bitOffset = 0; 140 141 long pos = readUntil(streamPos + len); 142 143 len = (int)Math.min((long)len, pos - streamPos); 145 if (len > 0) { 146 cache.seek(streamPos); 147 cache.readFully(b, off, len); 148 streamPos += len; 149 return len; 150 } else { 151 return -1; 152 } 153 } 154 155 165 public boolean isCached() { 166 return true; 167 } 168 169 178 public boolean isCachedFile() { 179 return true; 180 } 181 182 192 public boolean isCachedMemory() { 193 return false; 194 } 195 196 203 public void close() throws IOException { 204 super.close(); 205 cache.close(); 206 cacheFile.delete(); 207 stream = null; 208 StreamCloser.removeFromQueue(this); 209 } 210 } 211 | Popular Tags |