try 子句中的 BufferedReader:找不到符号

BufferReader inside try clause : cannot find symbol

我正在尝试编写一个 class 来处理读取文件。为了逐字阅读文件,我使用了以下在互联网上找到的代码。 Netbeans 似乎不同意并说它无法在 while 循环中找到符号 br。

public class Reader {
  public String file2string() {
    String line;
    try (InputStream fis = new FileInputStream("smth")) {
      InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
      BufferedReader br = new BufferedReader(isr);
    } catch (IOException ex) {
      Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex);
    }
    {
      while ((line = br.readLine()) != null) {
        String[] words = line.split(" ");
        // Now you have a String array containing each word in the current line
      }
    }
    return line;
  }
}

你的 try 语句后有一个 {}

{
    InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
    BufferedReader br = new BufferedReader(isr);
}

然后你有另一个 {} 块。

{
    while ((line = br.readLine()) != null) {
        String[] words = line.split(" ");
        // Now you have a String array containing each word in the current line
    }
}

在第一个块中声明的变量在第二个块中不可见。

合并两个块:

public String file2string() {
    String line;
    try (InputStream fis = new FileInputStream("smth")) {
        InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
        BufferedReader br = new BufferedReader(isr);
        while ((line = br.readLine()) != null) {
            String[] words = line.split(" ");           
        }
        return line;
    } catch (IOException ex) {
        Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex);
    }
    // you need to decide what you want to return here if you got an exception.
}

您似乎在拆分每一行并忽略结果,然后返回文件的最后一行。我不知道你为什么要那样做,或者你实际上想做什么;但这是修复编译错误的方法。

变量 "br" 在 try{} 块中声明,这就是它的作用域。它在该块之外是不可见的。尝试将 while 循环放在 try 块中。

您的循环在 try 之外,因此变量 br 在上下文中未知。将您的 while-loop 放入 try 结构中,如下所示:

public String file2string() {
    String line = null;
    try (InputStream fis = new FileInputStream("smth")) {
        InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
        BufferedReader br = new BufferedReader(isr);

        while ((line = br.readLine()) != null) {
            String[] words = line.split(" ");
            // Now you have a String array containing each word in the current line
        }
    } catch (IOException ex) {
        Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex);
    }  
    return line;
}