本文介绍了带有try块的Java BufferedReader错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一种应该加载文件的方法,但是它给了我这个错误:
I have this method that is supposed to load a file but it is giving me this error:
NamnMetod.java:175: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
BufferedReader inFil = new BufferedReader(new FileReader(fil));
^
NamnMetod.java:177: error: unreported exception IOException; must be caught or declared to be thrown
String rad = inFil.readLine();
^
这是我的代码:
public static void hämtaFrånText() {
try {
EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
String aktuellMapp = System.getProperty("user.dir");
JFileChooser fc = new JFileChooser(aktuellMapp);
int resultat = fc.showOpenDialog(null);
if (resultat != JFileChooser.APPROVE_OPTION) {
JOptionPane.showMessageDialog(null, "Ingen fil valdes!");
System.exit(0);
}
String fil = fc.getSelectedFile().getAbsolutePath();
String[] namn = new String[3];
String output ="";
BufferedReader inFil = new BufferedReader(new FileReader(fil));
String rad = inFil.readLine();
int antal = 0;
while(rad != null){
namn[antal] = rad;
rad = inFil.readLine();
antal++;
}
inFil.close();
}
});
}catch(IOException e2) {
JOptionPane.showMessageDialog(null,"The file was not found!");
}
}
我很困惑,因为我同时捕获了IOException和FileNotFoundException,但我仍然收到此错误...
I'm perplexed because i have caught both IOException and FileNotFoundException but I still get this error...
推荐答案
您在创建的代码中捕获了它们 Runnable
,而需要在 Runnable.run()
中捕获异常。
You are catching them in the code which creates the Runnable
, whereas the exceptions need to be caught in Runnable.run()
.
在您的 run
方法内移动try / catch。
Move the try/catch inside your run
method.
另外,使用try-with-resources来确保FileReader始终关闭,即使发生异常也是如此:
Also, use try-with-resources to ensure that the FileReader is always closed, even if an exception occurs:
try (FileReader fr = new FileReader(fil);
BufferedReader inFil = new BufferedReader(fr)) {
// ...
// No need to close `fr` or `inFil` explicitly.
}
这篇关于带有try块的Java BufferedReader错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!