# 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);

You Want To Have Those Changes Done Automatically?

The automatic application of this rule is supported in the following jSparrow version:

# Properties

Property Value
Rule ID UseFilesBufferedWriter
First seen in jSparrow version 3.22.0
Minimum Java version 7
Remediation cost 5 min
Links