【发布时间】:2019-01-06 15:25:49
【问题描述】:
对 Java 相当陌生,我正在尝试使用 fileChooser 打开文件并读取信息。我正处于尝试创建 fileInputStream 和inputStreamReader 的阶段。创建时,尽管文件存在,但我得到了FileNotFoundException。不太清楚为什么会发生这种情况,但我已将此代码放入 try/catch 块中以解决它。不幸的是,在编译变量“in”期间,我仍然收到cannot find symbol 错误。如果有人能对这些问题做出解释,将不胜感激。
openFileBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File("."));
fileChooser.setDialogTitle("Open your Rain Data.");
int returnVal = fileChooser.showOpenDialog(null);
//Handles when a file is opened by the user.
if (returnVal == JFileChooser.APPROVE_OPTION) {
String absolutePath = fileChooser.getSelectedFile().getAbsolutePath();
File file = new File(absolutePath);
try {
FileInputStream in = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(in);
} catch (FileNotFoundException ex) {
System.out.println("Error - the file was unable to be read by the rain handler. Check permissions and the file.");
} finally {
System.out.println(file.canRead());
System.out.println(file.exists());
System.out.println(in.available());
}
}
}
});
【问题讨论】:
-
发布完整的错误信息。
-
您已在
try块内声明了in,但您试图在它不在范围内的finally块中使用它。 -
@JacobG 已经指出 in 不能从 finally 块中访问。您还应该看看 try-with-resources。这将帮助您自动关闭流。
标签: java try-catch filenotfoundexception fileinputstream inputstreamreader