The Java BufferedWriter class is utilized to offer buffering for Writer objects, enhancing performance. This class is an extension of the Writer class. Buffering characters are employed to optimize the writing process of individual arrays, characters, and strings.
Class declaration
Now, let's examine the declaration of the Java.io.BufferedWriter class:
Example
public class BufferedWriter extends Writer
Class constructors
| Constructor | Description |
|---|---|
| BufferedWriter(Writer wrt) | It is used to create a buffered character output stream that uses the default size for an output buffer. |
| BufferedWriter(Writer wrt, int size) | It is used to create a buffered character output stream that uses the specified size for an output buffer. |
Class methods
| Method | Description |
|---|---|
| void newLine() | It is used to add a new line by writing a line separator. |
| void write(int c) | It is used to write a single character. |
| void write(char[] cbuf, int off, int len) | It is used to write a portion of an array of characters. |
| void write(String s, int off, int len) | It is used to write a portion of a string. |
| void flush() | It is used to flushes the input stream. |
| void close() | It is used to closes the input stream |
Example of Java BufferedWriter
Let's explore a basic illustration demonstrating how to write data to a text file named testout.txt by utilizing Java's BufferedWriter.
Example
package com.example;
import java.io.*;
public class BufferedWriterExample {
public static void main(String[] args) throws Exception {
FileWriter writer = new FileWriter("D:\\testout.txt");
BufferedWriter buffer = new BufferedWriter(writer);
buffer.write("Welcome to Java.");
buffer.close();
System.out.println("Success");
}
}
Output:
Output
success
testout.txt:
Example
Welcome to Java.