In this guide, you will learn about the Files newBufferedWriter() method in Java programming and how to use it with an example.
1. Files newBufferedWriter() Method Overview
Definition:
The Files.newBufferedWriter() method opens a file for writing, returning a BufferedWriter that may be used to write text to the file in an efficient manner.
Syntax:
static BufferedWriter newBufferedWriter(Path path, Charset cs, OpenOption... options)
Parameters:
- path: The path to the file to open or create.
- cs: The charset to use for encoding. If not specified, the default charset, which is Charset.defaultCharset(), is used.
- options: Options specifying how the file is opened. If no options are present, the file is created, truncated, or opened for writing.
Key Points:
- This method is intended for writing text files in a simple and efficient manner.
- The BufferedWriter ensures the file is properly closed after all bytes have been written or when an I/O error, or other runtime error, is detected.
- The method writes to the file directly without any buffering, making it suitable for writing to large files.
2. Files newBufferedWriter() Method Example
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class FilesBufferedWriterExample {
public static void main(String[] args) {
Path path = Paths.get("output.txt");
try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.CREATE)) {
writer.write("Hello, World!");
writer.newLine();
writer.write("This is a sample text.");
} catch (IOException e) {
System.out.println("Failed to write to the file: " + e.getMessage());
}
}
}
Output:
The file output.txt will contain: Hello, World! This is a sample text.
Explanation:
In this example, the Files.newBufferedWriter() method is used to create a BufferedWriter for the file output.txt. The StandardCharsets.UTF_8 charset is used for encoding.
The StandardOpenOption.CREATE option ensures that the file is created if it does not exist or opened if it does exist. Text is then written to the file using the write() method of the BufferedWriter and a new line is added using the newLine() method.
Comments
Post a Comment
Leave Comment