java: Using Buffered Reader and checking if String is null

Refresh

February 2019

Views

5.4k time

1

why doesn´t if (txtLine == null) { break; };work? or maybe the correct answer is why does it still set the string txtLine to null (literally). The way I understand it, it should break the moment the string is null? I don´t want it to set the string to "null". but stop when there are no more lines in the *.txt file

try{
    BufferedReader txtReader = new BufferedReader (new FileReader ("test.txt"));
    while (true) {
        // Reads one line.
        println(txtLine);
        if(txtLine == null){
            break;
        };
        txtLine = txtReader.readLine();
        nLines(txtLine);
    }
    txtReader.close();
} catch (IOException ex) {
    throw new ErrorException(ex);   
}

the txtFile variable is defined as an IVAR

private int nChars = 0;
private String txtLine = new String(); 
private ArrayList <String> array = new ArrayList <String>();

1 answers

4

I think the ordering of when you break and when you change the value of txtLine to be the next line read from the file is backwards, your code should look something like:

try{
    BufferedReader txtReader = new BufferedReader (new FileReader ("test.txt"));
    while (true) {
        // Reads one line.
        println(txtLine);
        txtLine = txtReader.readLine();
        // check after we read the value of txtLine
        if(txtLine == null){
            break;
        }

        nLines(txtLine);
    }
    txtReader.close();
} catch (IOException ex) {
    throw new ErrorException(ex);   
}

But this is a much more concise (and I think, clearer) form:

try{
    BufferedReader txtReader = new BufferedReader (new FileReader ("test.txt"));
    while ((txtLine = txtReader.readLine()) != null) {
        // Reads one line.
        println(txtLine);
        nLines(txtLine);
    }
    txtReader.close();
} catch (IOException ex) {
    throw new ErrorException(ex);   
}

Where while ((txtLine = txtReader.readLine()) != null) sets txtLine to the next line, and then checks that txtLine is not null before continuing.