Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Text lesson

Deleting File and Text in Java

BufferedWriter Class

Example: Using BufferedWriter(Writer out, int sz)

In this example, BufferedWriter is used with a specified buffer size. Adjusting the buffer size can improve performance depending on the size of data being written and system specifics.

package filewriting;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriterExample2 {
	public static void main(String[] args) {
		// This is actually the default size, but you can choose your own
		int bufferSize = 8192; //No of Characters
		try {
			BufferedWriter writer = new BufferedWriter
					(new FileWriter("example1.txt"), bufferSize);
			writer.write("Hello, this text uses a custom buffer size.");
			writer.newLine();
			writer.write("More efficient for large amounts of data.");
			System.out.println("The file writing operation completed!");
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 

Output

The file writing operation completed!

In this example, a larger buffer size may be beneficial if you’re writing large amounts of data at once. It reduces the number of physical disk writes by storing more data in memory before flushing it to disk.

 

Why Use BufferedWriter?

Using BufferedWriter over FileWriter directly provides a significant performance advantage when writing character data to a file, especially in cases where many small write operations occur.

The buffering minimizes the number of I/O operations, each of which could be costly due to the overhead of interacting with the disk.

 

 

 


 

End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

 

 

Submit a Review