gpt4 book ai didi

java - IOException 和 FileNotFoundException

转载 作者:行者123 更新时间:2023-11-29 06:16:47 26 4
gpt4 key购买 nike

这段代码有一些错误:

Error(18,40): unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown Error(19,42): unreported exception java.io.IOException; must be caught or declared to be thrown

但是当抛出 FileNotFound 和 IOException 异常时,编译器会显示这个错误:

Error(15,27): removeEldestEntry(java.util.Map.Entry) in cannot override removeEldestEntry(java.util.Map.Entry) in java.util.LinkedHashMap; overridden method does not throw java.io.IOException

有什么问题吗?代码在这里:

package client;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
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) {
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;
}

};


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());

}

}

最佳答案

试试这个..

package client;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.LinkedHashMap;
import java.util.Map;

public class Level1 {

private static final int max_cache = 50;
private Map cache = new LinkedHashMap(max_cache, .75F, true) {

@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
boolean removed = super.removeEldestEntry(eldest);
if (removed) {
FileOutputStream fos;
try {
fos = new FileOutputStream("t.tmp");

ObjectOutputStream oos = new ObjectOutputStream(fos);

oos.writeObject(eldest.getValue());

oos.close();

} catch (IOException ex) {
System.err.println("IOException!!");
} catch (FileNotFoundException ex) {
System.err.println("FileNotFoundException!!");
}
}
return removed;
}
};

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());

}

}
}

关于java - IOException 和 FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4817398/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com