【问题标题】:Cannot find Symbol in Java try block [duplicate]在 Java 尝试块中找不到符号 [重复]
【发布时间】: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


【解决方案1】:

在特定范围内定义的变量,例如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 子句确保:

finally 块在 try 块和任何 catch 块之后执行 无论控制如何离开 try 块或 捕获块。

通常您使用它来清除在try 正文中打开/使用的资源。
实际上filein 可能是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)){
     // ...
}

【讨论】:

    【解决方案2】:

    标准方法是:

    FileInputStream fileInputStream = null;
    try {
        fileInputStream = new FileInputStream(...);
        // do something with the inputstream
    } catch (IOException e) {
        // handle an exception
    } finally { //  finally blocks are guaranteed to be executed
        // close() can throw an IOException too, so we got to wrap that too
        try {
            if (fileInputStream != null) {
                fileInputStream.close();
            }        
        } catch (IOException e) {
            // handle an exception, or often we just ignore it
        }
    }
    

    所以在你的情况下:

    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);
              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());
                  try {
                      System.out.println(in.available());
                  } catch (IOException ex) {
                      // handle an exception, or often we just ignore it  
                  }
              }
          }
      }
    

    【讨论】:

      【解决方案3】:
      FileInputStream in = new FileInputStream(file); 
      

      在发布的问题中,引用“in”是在 try 块中创建的,因此它在该块内具有本地范围。首选是在 try 块之前声明它,以便有更大的范围。

      【讨论】:

        猜你喜欢
        • 2017-06-28
        • 2012-09-09
        • 2015-12-15
        • 1970-01-01
        • 1970-01-01
        • 2014-03-14
        • 2012-10-31
        • 1970-01-01
        相关资源
        最近更新 更多