【发布时间】:2011-01-27 15:17:44
【问题描述】:
如何覆盖 removeEldestEntry 方法以将最早的条目保存到文件?还有如何像我在 LinkedHashMap 中那样限制文件的大小。这是代码:
import java.util.*;
public class level1 {
private static final int max_cache = 50;
private Map cache = new LinkedHashMap(max_cache, .75F, true) {
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > max_cache;
}
};
public level1() {
for (int i = 1; i < 52; i++) {
String string = String.valueOf(i);
cache.put(string, string);
System.out.println("\rCache size = " + cache.size() +
"\tRecent value = " + i + " \tLast value = " +
cache.get(string) + "\tValues in cache=" +
cache.values());
}
我尝试使用 FileOutPutSTream :
private Map cache = new LinkedHashMap(max_cache, .75F, true) {
protected boolean removeEldestEntry(Map.Entry eldest) throws IOException {
boolean removed = super.removeEldestEntry(eldest);
if (removed) {
FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(eldest.getValue());
oos.close();
}
return removed;
}
但是我得到了一个错误
Error(15,27): removeEldestEntry(java.util.Map.Entry) in 无法覆盖 java.util.LinkedHashMap 中的 removeEldestEntry(java.util.Map.Entry);被覆盖的方法不会抛出 java.io.IOException
如果没有 IOExecptio,编译器会要求处理 IOexception 和 Filenotfoundexception。 也许存在另一种方式?请给我看示例代码,我是 java 新手,只是想了解 2 级缓存的基本原理。谢谢
【问题讨论】:
-
顺便说一句 super.removeEldestEntry(eldest) 总是返回 false。当您希望删除最旧的条目时,您必须覆盖它以返回 true。您的文件 t.tmp 将仅保存删除的最后一个条目。这是你想要的吗?
标签: java caching fileoutputstream linkedhashmap