Skip to main content

Command Palette

Search for a command to run...

SonarLint: "close()" calls should not be redundant

Published
1 min read
S

I love learning about technology and sharing that with others

From Java 7 when we use try with resource, try with resource will automatically handle closing of the resources and hence we don't need to close the resource manually.

Noncompliant Code Example

try (PrintWriter writer = new PrintWriter(process.getOutputStream())) {
  String contents = file.contents();
  writer.write(new Gson().toJson(new MyObject(contents)));
  writer.flush();
  writer.close();     // Noncompliant
}

Compliant Solution

try (PrintWriter writer = new PrintWriter(process.getOutputStream())) {
  String contents = file.contents();
  writer.write(new Gson().toJson(new MyObject(contents)));
  writer.flush();
}
9 views

More from this blog

H

hashcodehub

271 posts

Consistent, Passionate and Organized :)