1

Please see the code snippet

try (InputStream inputStream = this.getClass().getClassLoader()
                .getResourceAsStream("hello.txt");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {

But sonarQube complaints below error in the above line   

Correctness - Nullcheck of value previously dereferenced(line starting with BufferedReader ) .

Please help to resolve this issue  

Kampai
  • 22,848
  • 21
  • 95
  • 95
Anoop M Nair
  • 1,057
  • 1
  • 13
  • 31
  • I don't think this is the correct line. The error means that you are doing a null check but already accessed the variable. Can you show more code? – AndiCover Aug 14 '19 at 10:58
  • Are you checking for the nullness of `inputStream` anywhere within the try body? – RealSkeptic Aug 14 '19 at 11:15
  • 1
    I guess, that’s because the code analyzer uses the compiled code and in case of try-with-resource, [it’s a mess](https://stackoverflow.com/a/25746587/2711488), having unreachable code and redundant checks. But if that’s the cause for your problem, the good news is that you get rid of it when updating to JDK 11, even when compiling for `--release 8`. – Holger Aug 14 '19 at 11:29
  • 1
    By the way, you should use `this.getClass() .getResourceAsStream("/hello.txt")` instead of going through the class loader. This way, the access is compatible with modular software, as a class loader may have multiple modules, but you’re usually referring to the resource with the class’ module. Actually, if you’re not intending to allow resolving to different resources when executed for a subclass, you should use `ActualClassName.class .getResourceAsStream("/hello.txt")`. – Holger Aug 14 '19 at 11:44

1 Answers1

2

It's because getClassLoader().getResourceAsStream("hello.txt") can return null and you're using it just after to create the BufferedReader, without checking for null value.

Arnaud Claudel
  • 3,000
  • 19
  • 25