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级缓存的基本原理。谢谢     
已邀请:
首先需要确保您的方法正确覆盖父级。您可以对签名进行一些小的更改,例如只抛出一个更具体的已检查异常,该异常是在父级中声明的已检查异常的子类。在这种情况下,父级不会声明任何已检查的异常,因此您无法进一步优化,也不会抛出任何已检查的异常。所以你必须在当地处理
IOException
。有几种方法可以做到这一点,将其转换为某种类型的
RuntimeException
和/或记录它。 如果你担心文件大小,你可能不想只保留最后删除的条目,但很多 - 所以你应该打开文件进行追加。 你需要从方法返回
true
来实际删除eldest,你需要决定是否应该删除该元素。 使用文件时,您应该使用try / finally确保即使存在异常也关闭资源。这可能会有点难看 - 有时候有一个实用工具方法来完成关闭很好,所以你不需要额外的try / catch。 通常,您还应该对文件I / O使用一些缓冲,这可以大大提高性能;在这种情况下,使用将文件流包装在
java.io.BufferedOutputStream
中并将其提供给
ObjectOutputStream
。 这可能是你想做的事情:
private static final int MAX_ENTRIES_ALLOWED = 100;
private static final long MAX_FILE_SIZE = 1L * 1024 * 1024; // 1 MB

protected boolean removeEldestEntry(Map.Entry eldest) {
    if (size() <= MAX_ENTRIES_ALLOWED) {
        return false;
    }

    File objFile = new File("t.tmp");
    if (objFile.length() > MAX_FILE_SIZE) {
        // Do something here to manage the file size, such as renaming the file
        // You won't be able to easily remove an object from the file without a more
        // advanced file structure since you are writing arbitrary sized serialized
        // objects. You would need to do some kind of tagging of each entry or include
        // a record length before each one. Then you would have to scan and rebuild
        // a new file. You cannot easily just delete bytes earlier in the file without
        // even more advanced structures (like having an index, fixed size records and
        // free space lists, or even a database).
    }

    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(objFile, true); // Open for append
        ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(fos));

        oos.writeObject(eldest.getValue());
        oos.close(); // Close the object stream to flush remaining generated data (if any).
        return true;
    } catch (IOException e) {
        // Log error here or....
        throw new RuntimeException(e.getMessage(), e); // Convert to RuntimeException
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e2) {
                // Log failure - no need to throw though
            }
        }
    }
}
    
覆盖方法时,无法更改方法签名。因此,您需要在重写方法中处理异常而不是抛出异常。 这包含有关如何使用try和catch的一个很好的解释:http://download.oracle.com/javase/tutorial/essential/exceptions/try.html     

要回复问题请先登录注册