@@ -0,0 +1,2055 @@
+package edu.teco.dnd.util;%0A%0Aimport java.io.DataInputStream;%0Aimport java.io.File;%0Aimport java.io.FileInputStream;%0Aimport java.io.IOException;%0Aimport java.lang.ref.SoftReference;%0Aimport java.util.HashMap;%0Aimport java.util.Map;%0Aimport java.util.concurrent.locks.ReadWriteLock;%0Aimport java.util.concurrent.locks.ReentrantReadWriteLock;%0A%0A/**%0A * A cache for File data that uses SoftReferences to be memory friendly.%0A * %0A * @author Philipp Adolf%0A */%0Apublic class FileCache %7B%0A%09/**%0A%09 * The cache. If a File's data is loaded a SoftReference to the data is put in here.%0A%09 */%0A%09private final Map%3CFile, SoftReference%3Cbyte%5B%5D%3E%3E cache = new HashMap%3CFile, SoftReference%3Cbyte%5B%5D%3E%3E();%0A%09%0A%09/**%0A%09 * Used to synchronize access to %7B@link #cache%7D.%0A%09 */%0A%09private final ReadWriteLock lock = new ReentrantReadWriteLock();%0A%09%0A%09/**%0A%09 * Retrieves the File's data. If the File's data is cached the cached value is returned. Otherwise%0A%09 * the File is read and data is put into the cache. There is currently no way to invalidate a cache%0A%09 * entry (for example if a File has been modified).%0A%09 * %0A%09 * @param file the File to read%0A%09 * @return the contents of the File. May be a cached and potentially outdated version of the File.%0A%09 * @throws IOException if an error occurs while reading the File%0A%09 */%0A%09public byte%5B%5D getFileData(final File file) throws IOException %7B%0A%09%09SoftReference%3Cbyte%5B%5D%3E reference = null;%0A%09%09byte%5B%5D data = null;%0A%09%09%0A%09%09lock.readLock().lock();%0A%09%09try %7B%0A%09%09%09reference = cache.get(file);%0A%09%09%7D finally %7B%0A%09%09%09lock.readLock().unlock();%0A%09%09%7D%0A%09%09%0A%09%09if (reference != null) %7B%0A%09%09%09data = reference.get();%0A%09%09%09if (data != null) %7B%0A%09%09%09%09return data;%0A%09%09%09%7D%0A%09%09%7D%0A%09%09%0A%09%09data = new byte%5B(int) file.length()%5D;%0A%09%09final DataInputStream dis = new DataInputStream(new FileInputStream(file));%0A%09%09try %7B%0A%09%09%09dis.readFully(data);%0A%09%09%7D finally %7B%0A%09%09%09dis.close();%0A%09%09%7D%0A%09%09%0A%09%09lock.writeLock().lock();%0A%09%09try %7B%0A%09%09%09reference = cache.get(file);%0A%09%09%09if (reference == null %7C%7C reference.get() == null) %7B%0A%09%09%09%09cache.put(file, new SoftReference%3Cbyte%5B%5D%3E(data));%0A%09%09%09%7D%0A%09%09%7D finally %7B%0A%09%09%09lock.writeLock().unlock();%0A%09%09%7D%0A%09%09%0A%09%09return null;%0A%09%7D%0A%7D%0A

Add FileCache