对 Java 相当陌生,我正在尝试使用 fileChooser
打开文件并读取信息。我正处于尝试创建 fileInputStream 和 inputStreamReader
的阶段。创建时我得到了 FileNotFoundException
尽管该文件存在。不太清楚为什么会发生这种情况,但我已将此代码放入 try/catch
中 block 来解决它。不幸的是,我仍然得到一个 cannot find symbol
编译期间变量“in”出错。如果有人能够对这些问题做出解释,我们将不胜感激。
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
body)仅在此范围内可见。因此,在 try
主体之外,无法访问该变量。
实际上你应该在之前声明它:
File file = new File(absolutePath);
FileInputStream in = null;
try {
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());
}
请注意,这是 finally
的错误用法。
finally
子句确保:
the finally block is executed after the try block and any catch block that might be executed, no matter how control leaves the try block or catch block.
通常,您使用它来清除 try
正文中打开/使用的资源。
实际上file
或in
可能是null
。因此,此代码可能会在运行时因 NullPointerException
失败。
除了你的代码抛出一些 IOException 之外,你还应该捕获它们,而不仅仅是错误处理中的 FileNotFoundException
:
这种处理只能在try
中执行,例如:
try {
in = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(in);
System.out.println(file.canRead());
System.out.println(file.exists());
System.out.println(in.available());
}
catch (FileNotFoundException ex) {
System.out.println("Error - the file was unable to be read by the rain handler. Check permissions and the file.");
}
catch (IOException ex) {
System.out.println("Error...");
}
更好的方法是依靠尝试资源来自动关闭流资源:
try (FileInputStream in = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(in)){
// ...
}
关于java - 在 Java try block 中找不到符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54062998/