1:
37:
38:
39: package ;
40:
41: import ;
42: import ;
43: import ;
44: import ;
45:
46:
49: public class FileCacheImageOutputStream extends ImageOutputStreamImpl
50: {
51: private OutputStream stream;
52: private File cacheFile;
53: private RandomAccessFile cache;
54: private long maxPos;
55:
56: public FileCacheImageOutputStream(OutputStream s, File cacheDir)
57: throws IOException
58: {
59: stream = s;
60: cacheFile = File.createTempFile("imageio", ".tmp", cacheDir);
61: cache = new RandomAccessFile(cacheFile, "rw");
62: maxPos = 0;
63: }
64:
65: public void close()
66: throws IOException
67: {
68: maxPos = cache.length();
69: seek(maxPos);
70: flushBefore(maxPos);
71: super.close();
72: cache.close();
73: cacheFile.delete();
74: stream.flush();
75: stream = null;
76: }
77:
78: public boolean isCached()
79: {
80: return true;
81: }
82:
83: public boolean isCachedFile()
84: {
85: return true;
86: }
87:
88: public boolean isCachedMemory()
89: {
90: return false;
91: }
92:
93: public int read()
94: throws IOException
95: {
96: bitOffset = 0;
97: int val = cache.read();
98: if (val != -1)
99: streamPos++;
100: return val;
101: }
102:
103: public int read(byte[] data, int offset, int len)
104: throws IOException
105: {
106: bitOffset = 0;
107: int num = cache.read(data, offset, len);
108: if (num != -1)
109: streamPos += num;
110: return num;
111: }
112:
113: public void write(byte[] data, int offset, int len)
114: throws IOException
115: {
116: flushBits();
117: cache.write(data, offset, len);
118: streamPos += len;
119: maxPos = Math.max(streamPos, maxPos);
120: }
121:
122: public void write(int value)
123: throws IOException
124: {
125: flushBits();
126: cache.write(value);
127: streamPos++;
128: maxPos = Math.max(streamPos, maxPos);
129: }
130:
131: public long length()
132: {
133: long l;
134: try
135: {
136: l = cache.length();
137: }
138: catch (IOException ex)
139: {
140: l = -1;
141: }
142: return l;
143: }
144:
145: public void seek(long pos)
146: throws IOException
147: {
148: checkClosed();
149: if (pos < flushedPos)
150: throw new IndexOutOfBoundsException();
151: cache.seek(pos);
152: streamPos = cache.getFilePointer();
153: maxPos = Math.max(streamPos, maxPos);
154: bitOffset = 0;
155: }
156:
157: public void flushBefore(long pos)
158: throws IOException
159: {
160: long oldPos = flushedPos;
161: super.flushBefore(pos);
162: long flushed = flushedPos - oldPos;
163: if (flushed > 0)
164: {
165: int len = 512;
166: byte[] buf = new byte[len];
167: cache.seek(oldPos);
168: while (flushed > 0)
169: {
170: int l = (int) Math.min(flushed, len);
171: cache.readFully(buf, 0, l);
172: stream.write(buf, 0, l);
173: flushed -= l;
174: }
175: stream.flush();
176: }
177: }
178: }