# 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.

Use a Java Refactoring Tool

No license required

You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.

System-wide Refactoring

Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.

a drawn cute bird pointing at a graph that shows positive results

# Properties

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