2003/11/03 07:36:40
[org.ibex.core.git] / src / org / xwt / util / CachedInputStream.java
index d46569e..a599459 100644 (file)
@@ -1,6 +1,7 @@
 package org.xwt.util;
 import java.io.*;
 
+// FEATURE: don't use a byte[] if we have a diskCache file
 /**
  *  Wraps around an InputStream, caching the stream in a byte[] as it
  *  is read and permitting multiple simultaneous readers
@@ -12,9 +13,19 @@ public class CachedInputStream {
     byte[] cache = new byte[1024 * 128];
     int size = 0;
     final InputStream is;
+    File diskCache;
 
-    public CachedInputStream(InputStream is) { this.is = is; }
-    public InputStream getInputStream() { return new SubStream(); }
+    public CachedInputStream(InputStream is) { this(is, null); }
+    public CachedInputStream(InputStream is, File diskCache) {
+        this.is = is;
+        this.diskCache = diskCache;
+    }
+    public InputStream getInputStream() throws IOException {
+        System.out.println("diskCache == " + diskCache);
+        System.out.println("diskCache.exists() == " + diskCache.exists());
+        if (diskCache != null && diskCache.exists()) return new FileInputStream(diskCache);
+        return new SubStream();
+    }
 
     public void grow(int newLength) {
         if (newLength < cache.length) return;
@@ -28,7 +39,21 @@ public class CachedInputStream {
         filling = true;
         grow(size + howMuch);
         int ret = is.read(cache, size, howMuch);
-        if (ret == -1) eof = true;
+        if (ret == -1) {
+            eof = true;
+            // FIXME: probably a race here
+            if (diskCache != null && !diskCache.exists())
+                try {
+                    File cacheFile = new File(diskCache + ".tmp");
+                    FileOutputStream cacheFileStream = new FileOutputStream(cacheFile);
+                    cacheFileStream.write(cache, 0, size);
+                    cacheFileStream.close();
+                    cacheFile.renameTo(diskCache);
+                } catch (IOException e) {
+                    Log.log(this, "exception thrown while writing disk cache");
+                    Log.log(this, e);
+                }
+        }
         else size += ret;
         filling = false;
         notifyAll();