01: package ri.cache.loader;
02:
03: import javax.cache.spi.CacheLoader;
04: import javax.cache.spi.CacheLoaderException;
05: import java.io.File;
06: import java.io.FileInputStream;
07: import java.io.IOException;
08: import java.io.InputStream;
09:
10: /**
11: * FileLoader
12: *
13: * @author Brian Goetz
14: */
15: public class FileLoader extends AbstractCacheLoader<String, byte[]>
16: implements CacheLoader<String, byte[]> {
17: private final File rootDirectory;
18:
19: public FileLoader(File rootDirectory) {
20: this .rootDirectory = rootDirectory;
21: }
22:
23: public FileLoader(String rootDirectory) {
24: this (new File(rootDirectory));
25: }
26:
27: public byte[] load(String key) throws CacheLoaderException {
28: File f = new File(rootDirectory, (String) key);
29: try {
30: long length = f.length();
31: if (length > Integer.MAX_VALUE)
32: throw new CacheLoaderException(
33: "FileLoader: file is too long");
34:
35: int bytesLeft = (int) length;
36: byte[] bytes = new byte[bytesLeft];
37:
38: InputStream is = new FileInputStream(f);
39: try {
40: while (bytesLeft > 0)
41: bytesLeft -= is.read(bytes, (int) length
42: - bytesLeft, bytesLeft);
43: return bytes;
44: } catch (IOException e) {
45: throw new CacheLoaderException(
46: "IOException reading file "
47: + f.getAbsolutePath(), e);
48: } finally {
49: is.close();
50: }
51: } catch (IOException e) {
52: throw new CacheLoaderException("IOException reading file "
53: + f.getAbsolutePath(), e);
54: }
55: }
56: }
|