Java BufferedWriter Class
In Java, writing to files efficiently is an essential task in many applications. The BufferedWriter
class, part of the java.io
package, is specifically designed to provide efficient writing of text data. By buffering the output, it reduces the number of write operations, improving performance when writing large amounts of text data. In this blog post, we’ll take a deep dive into the BufferedWriter
class, explore its functionality, and walk you through examples of its usage.
The BufferedWriter
class in Java is a character-based output stream that is used to write text data to a file or another output stream. It is a wrapper around a Writer class (like FileWriter
) and provides a buffer to make writing more efficient by minimizing the number of write operations.
newLine()
method allows you to add platform-specific newlines to separate lines of text..txt
, .csv
, .json
, and .xml
.To use BufferedWriter
, you need to create an object of BufferedWriter
and pass a Writer
object (like FileWriter
) as a parameter.
BufferedWriter(Writer out)
For example, to write to a file using BufferedWriter
, you would pass a FileWriter
object to it:
BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt"));
You can also specify if you want to append to an existing file:
BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt", true));
The primary method for writing data using BufferedWriter
is write()
. Additionally, the newLine()
method is used to insert new lines. Let's go through some practical examples to better understand how to use this class.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriterExample {
public static void main(String[] args) {
BufferedWriter writer = null;
try {
// Create a BufferedWriter to write to the file
writer = new BufferedWriter(new FileWriter("example.txt"));
// Write data to the file
writer.write("Hello, World!");
writer.newLine(); // Insert a new line
writer.write("Welcome to the BufferedWriter class example.");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// Close the BufferedWriter
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
BufferedWriter
is created with a FileWriter
to write to the example.txt
file.write()
method is used to write the text to the file.newLine()
method is called to insert a platform-specific newline character (it could be \n
on Unix-based systems or \r\n
on Windows).finally
block ensures that the BufferedWriter
is properly closed after writing.If you want to append data to an existing file, you can use the second constructor of FileWriter
, which accepts a boolean parameter append
. When set to true
, the BufferedWriter
will append new data instead of overwriting the existing file content.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriterAppendExample {
public static void main(String[] args) {
BufferedWriter writer = null;
try {
// Create a BufferedWriter in append mode
writer = new BufferedWriter(new FileWriter("example.txt", true));
// Append new data to the file
writer.newLine(); // Insert a new line
writer.write("This content is being appended to the file.");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// Close the BufferedWriter
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
true
as the second parameter to FileWriter
, which tells the BufferedWriter
to append data instead of overwriting the file.To write multiple lines of text to a file, you can use the write()
method multiple times and call newLine()
in between to separate each line.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriterMultipleLines {
public static void main(String[] args) {
BufferedWriter writer = null;
try {
// Create a BufferedWriter to write to the file
writer = new BufferedWriter(new FileWriter("multipleLines.txt"));
// Write multiple lines to the file
writer.write("This is the first line.");
writer.newLine();
writer.write("This is the second line.");
writer.newLine();
writer.write("This is the third line.");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// Close the BufferedWriter
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
write()
to write each line and newLine()
to add a newline between them.The BufferedWriter
class is specifically designed to enhance performance. By buffering the output and writing data in larger chunks, it minimizes the number of I/O operations required, making it more efficient than writing one character at a time with FileWriter
or PrintWriter
.
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
public class PerformanceComparison {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
// Using FileWriter
try (FileWriter writer = new FileWriter("largefile.txt")) {
for (int i = 0; i < 1000000; i++) {
writer.write("This is a test line.\n");
}
} catch (IOException e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.println("FileWriter time: " + (endTime - startTime) + " milliseconds");
startTime = System.currentTimeMillis();
// Using BufferedWriter
try (BufferedWriter writer = new BufferedWriter(new FileWriter("largefile.txt"))) {
for (int i = 0; i < 1000000; i++) {
writer.write("This is a test line.\n");
}
} catch (IOException e) {
e.printStackTrace();
}
endTime = System.currentTimeMillis();
System.out.println("BufferedWriter time: " + (endTime - startTime) + " milliseconds");
}
}
BufferedWriter
can write large amounts of data compared to FileWriter
.BufferedWriter
in a finally
block or use the try-with-resources statement to avoid resource leaks.newLine()
method to add new lines to your file to ensure platform-specific line breaks.IOException
when writing to a file to deal with any potential issues like file permissions or disk space.