BufferedWriter in Java
BufferedWriter in Java is a Writer that buffers the stream of characters before writing them to an underlying output stream.
It adds the buffering capability to the underlying output character stream, so that there is no need to access the underlying file system for each read and write operation.
When a program writes to a BufferedWriter, the text is stored in the buffer.
When the buffer is filled up or explicitly flushed, the text is moved to the underlying output stream that makes the writes much faster and improves the performance.
Java Bufferedwriter Class Declaration
BufferedWriter class is a subclass of Writer class that extends Object class. It implements Closeable, Flushable, Appendable, and AutoCloseable interfaces.
The general syntax to declare BufferedWriter class in Java is as follows:
public class BufferedWriter
extends Writer
implements Closeable, Flushable, Appendable, AutoCloseable
The inheritance hierarchy for BufferedWriter class is as follows:
java.lang.Object
java.io.Writer
java.io.BufferedWriter
BufferedWriter class was added in Java 1.1 version. It is defined in the java.io.BufferedWriter package that is imported into the program before using it.
Constructors of BufferedWriter Class
A BufferedWriter class has two constructors in Java that allow passing a Writer object. They are as follows:
- BufferedWriter(Writer out)
- BufferedWriter(Writer out, int size)
1. BufferedWriter(Writer out): This constructor creates a buffered writer object that buffers the character output stream specified by out. It uses a default buffer size.
The general syntax to create BufferedWriter object with default size is as follows:
BufferedWriter bw = new BufferedWriter(Writer out);
For example, we can wrap the FileWriter with BufferedWriter by using the following lines of code:
FileWriter fw = new FileWriter("myfile.txt");
BufferedWriter bw = new BufferedWriter(fw);
Thus, Java BufferedWriter warps another Writer and adds a buffer that will write the text much faster and improve performance by buffering output.
2. BufferedWriter(Writer out, int size): This constructor creates a buffered writer object that buffers character output stream out with specified buffer size.
Simple Steps for Buffering a Character-Based File Stream
There are the following steps for buffering the character-based file stream that is as follows:
1. Construct the underlying output stream. It will be an object of FileWriter.
2. Wrap the file stream in the appropriate buffered writer using Java BufferedWriter class.
3. Perform all I/O operations through the buffered writer.
4. At last, close the buffered output stream.
Methods of BufferedWriter Class in Java
In addition to methods inherited from the Writer class, BufferedWriter class also provides some useful methods that are as follows:
1. void flush(): This method flushes the stream.
2. void newLine(): This method writes a newline character as defined by the line separator. The newLine() method is useful when we want a line separator in the output. There is no need to include a newline character ‘\n’ in the text.
3. void write(char[ ] cbuf, int offset, int length): This method writes a segment of an array of characters, starting at the position offset.
4. void write(int c): This method is used to write a single character c.
5. void write(String s, int offset, int length): This method writes a segment of a String, starting at the position offset.
All the BufferedWriter class methods can throw an exception named IOException if any error occurs.
Example Program of BufferedWriter class
Example 1: Let’s take a simple Java program where we will write lines of text into the file using BufferedWriter class.
package javaPackage;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriterExample {
public static void main(String[] args) throws IOException
{
// Create an object of FileWriter class.
FileWriter fw = new FileWriter("D:\\myfile.txt");
// Create an object of BufferedWriter class and reference variable fw to its constructor.
BufferedWriter bw = new BufferedWriter(fw);
bw.write("This is an apple");
bw.newLine(); // For line separator.
bw.write("This is an orange");
bw.close(); // Closing the stream.
System.out.println("File written successfully.");
}
}
Output: File written successfully.
Contents written into file:
This is an apple This is an orange
Example 2: Let’s take another Java program based on the use of BufferedWriter class.
package javaPackage;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriterExample {
public static void main(String[] args) throws IOException
{
String[] strs = {"New Delhi is the capital of India.",
"Washington, D.C. is the capital of US.",
"Canberra is the capital of Australia."
};
// Create an object of FileWriter class.
FileWriter fw = new FileWriter("D:\\myfile.txt");
// Create an object of BufferedWriter class and reference variable fw to its constructor.
BufferedWriter bw = new BufferedWriter(fw);
for(int i = 0; i < strs.length; i++)
{
bw.write(strs[i]);
bw.newLine();
}
bw.close(); // Closing the stream.
System.out.println("File written successfully.");
}
}
Output: File written successfully.
Contents written to file:
New Delhi is the capital of India. Washington, D.C. is the capital of US. Canberra is the capital of Australia.
Example 3: Let us write a simple Java program in which we will use BufferedWriter in Java to write some text to a file.
package javaProgram;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class SimpleBufferedWriterExample {
public static void main(String[] args) {
BufferedWriter bw = null;
try {
// Create an object of FileWriter class to write to a file named "example.txt"
FileWriter fw = new FileWriter("example.txt");
// Wrap the FileWriter in a BufferedWriter for efficient writing
bw = new BufferedWriter(fw);
// Write some text to the file
bw.write("Hello, World!");
bw.newLine(); // Adds a new line
bw.write("This is an example of using BufferedWriter.");
System.out.println("File written successfully");
} catch (IOException e) {
// Handle any IO exceptions here
e.printStackTrace();
} finally {
// Ensure the BufferedWriter is closed properly
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
// Handle potential IO exception on close
e.printStackTrace();
}
}
}
}
}
Output: File written successfully
Contents written to the text “example.txt” file is as:
Hello, World! This is an example of using BufferedWriter.
In this example, we have created an object of FileWriter class to write character files. Its constructor takes the name of file as an argument.
Then, we have created an object of BufferedWriter class and wrapped a FileWriter to buffer the input and improve efficiency by reducing the number of writes to the disk.
The statement bw.write(String s); writes a string to the buffered writer. The statement bw.newLine(); adds a new line in the file by writing a line separator.
We have used try-catch-finally block. This block ensures that the BufferedWriter is closed properly in the finally block, even if an exception occurs during writing. Closing the buffered writer also closes the underlying writer (FileWriter).
In this tutorial, you learned about BufferedWriter class in Java with example programs. I hope that you will have understood the basic concepts of BufferedWriter class. In the next, we will learn PrintWriter class in Java with examples. Please email us if you find anything incorrect in this tutorial. Your email is valuable to us.
Thanks for reading!!!