1 7 8 package javax.imageio.stream; 9 10 import java.io.IOException ; 11 import java.io.OutputStream ; 12 13 25 public class MemoryCacheImageOutputStream extends ImageOutputStreamImpl { 26 27 private OutputStream stream; 28 29 private MemoryCache cache = new MemoryCache (); 30 31 40 public MemoryCacheImageOutputStream(OutputStream stream) { 41 if (stream == null) { 42 throw new IllegalArgumentException ("stream == null!"); 43 } 44 this.stream = stream; 45 } 46 47 public int read() throws IOException { 48 checkClosed(); 49 50 bitOffset = 0; 51 52 int val = cache.read(streamPos); 53 if (val != -1) { 54 ++streamPos; 55 } 56 return val; 57 } 58 59 public int read(byte[] b, int off, int len) throws IOException { 60 checkClosed(); 61 62 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 bytesLeftInCache = cache.getLength() - streamPos; 80 if (bytesLeftInCache <= 0) { 81 return -1; } 83 84 len = (int)Math.min(bytesLeftInCache, (long)len); 88 cache.read(b, off, len, streamPos); 89 streamPos += len; 90 return len; 91 } 92 93 public void write(int b) throws IOException { 94 checkClosed(); 95 flushBits(); 96 cache.write(b, streamPos); 97 ++streamPos; 98 } 99 100 public void write(byte[] b, int off, int len) throws IOException { 101 checkClosed(); 102 flushBits(); 103 cache.write(b, off, len, streamPos); 104 streamPos += len; 105 } 106 107 public long length() { 108 return cache.getLength(); 109 } 110 111 121 public boolean isCached() { 122 return true; 123 } 124 125 134 public boolean isCachedFile() { 135 return false; 136 } 137 138 147 public boolean isCachedMemory() { 148 return true; 149 } 150 151 157 public void close() throws IOException { 158 long length = cache.getLength(); 159 seek(length); 160 flushBefore(length); 161 super.close(); 162 cache.reset(); 163 stream = null; 164 } 165 166 public void flushBefore(long pos) throws IOException { 167 long oFlushedPos = flushedPos; 168 super.flushBefore(pos); 169 170 long flushBytes = flushedPos - oFlushedPos; 171 cache.writeToStream(stream, oFlushedPos, flushBytes); 172 cache.disposeBefore(flushedPos); 173 stream.flush(); 174 } 175 } 176 | Popular Tags |