Majd Majd - 3 months ago 9
Java Question

BufferReader inside try clause : cannot find symbol

please keep in mmind that my java knowledge is pretty basic.

I'm trying to write a class that handles reading files. In order to read the file word by word i used the following code i found around the internet. Netbeans seems to disagree and says that he cannot find the symbole br inside the while.

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;
}
}

Answer

Your loop is out the try so the variable br is unknown in the context. Put your while-loop inside the try structure like here:

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;
}