简体   繁体   中英

java: Using Buffered Reader and checking if String is null

why doesn´t if (txtLine == null) { break; }; 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>();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM