# Remove Redundant Close

# Description

In Java, the try-with-resource statements are able to automatically close the resources which are defined in the try-with-resource header. Thus, any explicit close() (opens new window) invocation in the try block is redundant and potentially confusing. This rule eliminates redundant resource close() invocations.

# Benefits

Applying this rule removes unnecessary code.

# Tags

# Code Changes

# Remove Close For One Resource

Pre

try (BufferedReader br = new BufferedReader(new FileReader(path))) {
	System.out.println("First line: " + br.readLine());
	br.close();
} catch (IOException e) {
	e.printStackTrace();
}

Post

try (BufferedReader br = new BufferedReader(new FileReader(path))) {
	System.out.println("First line: " + br.readLine());
} catch (IOException e) {
	e.printStackTrace();
}

# Remove Close For Resource Declared Outside The Header

Pre

BufferedReader br = new BufferedReader(new FileReader(path));
try (br) {
	System.out.println("First line: " + br.readLine());
	br.close();
} catch (IOException e) {
	e.printStackTrace();
}

Post

BufferedReader br = new BufferedReader(new FileReader(path));
try (br) {
	System.out.println("First line: " + br.readLine());
} catch (IOException e) {
	e.printStackTrace();
}

# Remove Close For Multiple Resources

Pre

try (BufferedReader br = new BufferedReader(new FileReader(path));
		BufferedReader br2 = new BufferedReader(new FileReader(path2))) {
	System.out.println("First line of first file: " + br.readLine());
	br.close();
	System.out.println("First line of second file " + br2.readLine());
	br2.close();
} catch (IOException e) {
	e.printStackTrace();
}

Post

try (BufferedReader br = new BufferedReader(new FileReader(path));
		BufferedReader br2 = new BufferedReader(new FileReader(path2))) {
	System.out.println("First line of first file: " + br.readLine());
	System.out.println("First line of second file " + br2.readLine());
} catch (IOException e) {
	e.printStackTrace();
}

# Limitations

The 'close()'-invocation statement can only be removed if the resource is a local variable which is declared in the same scope.

🛠️ Auto-refactor Available

You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

Property Value
Rule ID RemoveRedundantClose
First seen in jSparrow version 4.11.0
Minimum Java version 7
Remediation cost 2 min
Links