# Use Files.newBufferedWriter

# Description

Java 7 introduced the Files (opens new window) class that contains convenience methods for operating on files. This rule makes use of the Files.newBufferedWriter (opens new window) method for initializing BufferedWriter (opens new window) objects to write text files in an efficient non-blocking manner.

# Benefits

Achieve better performance by using non-blocking I/O operations offered by the java.nio (opens new window) package.

# Tags

# Code Changes

# Creating the BufferedWriter from a new FileWriter

Pre

String location = "path/to/file";
BufferedWriter bw = new BufferedWriter(new FileWriter(location));

Post

String location = "path/to/file";
BufferedWriter bw = Files.newBufferedWriter(Paths.get(location), Charset.defaultCharset());

# Creating the FileWriter from a new File

Pre

String location = "path/to/file";
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(location)));

Post

String location = "path/to/file";
BufferedWriter bw = Files.newBufferedWriter(Paths.get(location), Charset.defaultCharset());

# Declaring the Resources on a Try-With-Resource Statement

Pre

try (FileWriter writer = new FileWriter(new File("path/to/file"));
		BufferedWriter bw = new BufferedWriter(writer)) {
    //...
} catch (IOException e) {}

Post

try (BufferedWriter bw = Files.newBufferedWriter(Paths.get("path/to/file"), Charset.defaultCharset())) {
	// ...
} catch (IOException e) {}

# Providing the Charset Manually (Since Java 11)

Pre

String location = "path/to/file";
BufferedWriter bw = new BufferedWriter(new FileWriter(location, StandardCharsets.UTF_8));

Post

String location = "path/to/file";
BufferedWriter bw = Files.newBufferedWriter(Paths.get(location), StandardCharsets.UTF_8);

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 UseFilesBufferedWriter
First seen in jSparrow version 3.22.0
Minimum Java version 7
Remediation cost 5 min
Links