001: /*
002: * Licensed to the Apache Software Foundation (ASF) under one or more
003: * contributor license agreements. See the NOTICE file distributed with
004: * this work for additional information regarding copyright ownership.
005: * The ASF licenses this file to You under the Apache License, Version 2.0
006: * (the "License"); you may not use this file except in compliance with
007: * the License. You may obtain a copy of the License at
008: *
009: * http://www.apache.org/licenses/LICENSE-2.0
010: *
011: * Unless required by applicable law or agreed to in writing, software
012: * distributed under the License is distributed on an "AS IS" BASIS,
013: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014: * See the License for the specific language governing permissions and
015: * limitations under the License.
016: */
017:
018: package javax.imageio.stream;
019:
020: import java.io.*;
021:
022: public class FileCacheImageInputStream extends ImageInputStreamImpl {
023: private InputStream is;
024: private File file;
025: private RandomAccessFile raf;
026:
027: public FileCacheImageInputStream(InputStream stream, File cacheDir)
028: throws IOException {
029: if (stream == null) {
030: throw new IllegalArgumentException("stream == null!");
031: }
032: is = stream;
033:
034: if (cacheDir == null || cacheDir.isDirectory()) {
035: file = File.createTempFile(
036: FileCacheImageOutputStream.IIO_TEMP_FILE_PREFIX,
037: null, cacheDir);
038: file.deleteOnExit();
039: } else {
040: throw new IllegalArgumentException("Not a directory!");
041: }
042:
043: raf = new RandomAccessFile(file, "rw");
044: }
045:
046: @Override
047: public int read() throws IOException {
048: bitOffset = 0;
049:
050: if (streamPos >= raf.length()) {
051: int b = is.read();
052:
053: if (b < 0) {
054: return -1;
055: }
056:
057: raf.seek(streamPos++);
058: raf.write(b);
059: return b;
060: }
061:
062: raf.seek(streamPos++);
063: return raf.read();
064: }
065:
066: @Override
067: public int read(byte[] b, int off, int len) throws IOException {
068: bitOffset = 0;
069:
070: if (streamPos >= raf.length()) {
071: int nBytes = is.read(b, off, len);
072:
073: if (nBytes < 0) {
074: return -1;
075: }
076:
077: raf.seek(streamPos);
078: raf.write(b, off, nBytes);
079: streamPos += nBytes;
080: return nBytes;
081: }
082:
083: raf.seek(streamPos);
084: int nBytes = raf.read(b, off, len);
085: streamPos += nBytes;
086: return nBytes;
087: }
088:
089: @Override
090: public boolean isCached() {
091: return true;
092: }
093:
094: @Override
095: public boolean isCachedFile() {
096: return true;
097: }
098:
099: @Override
100: public boolean isCachedMemory() {
101: return false;
102: }
103:
104: @Override
105: public void close() throws IOException {
106: super.close();
107: raf.close();
108: file.delete();
109: }
110: }
|