我试图读取使用 JFileChooser 打开的文件,但出现以下错误
error: unreported exception FileNotFoundException; must be caught or declared to be thrown
BufferedReader br = new BufferedReader(new FileReader(file));
这是代码片段:
class LoadFile implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
File f = new File("/home/ralf/Documents");
String line = null;
chooser.setCurrentDirectory(f);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
BufferedReader br = new BufferedReader(new FileReader(file));
try {
while((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (FileNotFoundException fnfe) {
JOptionPane.showMessageDialog(null, fnfe.getMessage());
return;
} catch (IOException ex) {
ex.printStackTrace();
}
} else {
}
}
}
注意:类 LoadFile 可在扩展 JFrame 的类 Animation(未显示)中找到。我将按钮放在类 Animation 构造函数中,并从那里调用 LoadFile 的 actionPerformed。