removeEldestEntry覆盖
如何覆盖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;
}
但我收到了一个错误
错误(15,27):removeEldestEntry(java.util.Map.Entry)in不能覆盖java.util.LinkedHashMap中的removeEldestEntry(java.util.Map.Entry);重写方法不会抛出java.io.IOException
没有IOExecptio编译器要求处理IOexception和Filenotfoundexception。
也许存在另一种方式?请给我看一些示例代码,我是java的新手,只是想了解2级缓存的基本原理。谢谢
没有找到相关结果
已邀请:
2 个回复
葛瞎说漓
。有几种方法可以做到这一点,将其转换为某种类型的
和/或记录它。 如果你担心文件大小,你可能不想只保留最后删除的条目,但很多 - 所以你应该打开文件进行追加。 你需要从方法返回
来实际删除eldest,你需要决定是否应该删除该元素。 使用文件时,您应该使用try / finally确保即使存在异常也关闭资源。这可能会有点难看 - 有时候有一个实用工具方法来完成关闭很好,所以你不需要额外的try / catch。 通常,您还应该对文件I / O使用一些缓冲,这可以大大提高性能;在这种情况下,使用将文件流包装在
中并将其提供给
。 这可能是你想做的事情:
孝箱捆讨