Java: null comparison always gives false: wrong warning?

An interesting situation. I have a section of code that creates several ZipOutputStreams. As a security check, before I even think about writing everything that I check, my output streams were correctly initialized:

ZipOutputStream countStream = null;
File countFile = null;
// other files

try {
    countFile =
    new File(savePath.getCanonicalPath() + savePath.separator + outputTag
        + "_COUNT_OUTPUTS.zip");
    // other files
} catch (Exception e) {
    outputLog.add("UNABLE TO FIND SAVE PATH");
    return util.FILE_INVALID;
}

try {
    // prepare outputs
    if (countFile.exists() == true) {
    countFile.delete();
    } else {
    }
    countStream = new ZipOutputStream(new FileOutputStream(countFile));
    // other files
} catch (Exception e) {
    e.printStackTrace();
    outputLog.add("UNABLE TO CREATE OUTPUT FILES");
    return util.FILE_SAVE_FAIL;
}

if (countStream == null) {
    outputLog.add("UNABLE TO CREATE OUTPUT FILES");
    return util.FILE_SAVE_FAIL;
} else {
}

I don’t particularly see where the problem is in this code, but it triggers a warning about the null test: "Zero comparison always gives false: the countStream variable cannot be null in this place." As far as I can see this, I have a variable with initialization to zero, then an attempt is made to create an output stream, but it is not guaranteed. ignoring the warning is simple enough, but I'd better know how the compiler concludes that countStream is guaranteed to be successfully created.

K.Barad

+3
3

, null :

  • try, (countStream = new ....)
  • catch "return" .

, "if (countStream == null)" , countStream ZipOutputStream.

+6

, countStream . , return util.FILE_SAVE_FAIL . , , , .

: , , countStream null .

+4

From this code, I realized that countStream is null, and therefore its warning that "Zero comparison always gives false"

If you are debugging, you will find that this code always goes into else because the condition if (countStream == null) {does not pass.

0
source

Source: https://habr.com/ru/post/1794654/


All Articles