BufferedWriter

Use of FileReader and FileWriter is not recommended because :

  • While Writing Data by FileWriter we have to insert line separator manually, which is varied from System to System. It is difficult to the programmer.
  • While Reading Data by using FileReader we can read data character by character which is not convenient to the programmer.

To overcome these limitations we should go for BufferedWriter and BufferedReader.

Constructor :

BufferedWriter bw = new BufferedWriter(Write w);
BufferedWriter bw = new BufferedWriter(Write w, int buffersie);

Note : BufferedWriter can’t communicate directly with a file , it has to communicate via some Writer object only.

Which of the following are valid?

BufferedWriter bw = new BufferedWriter("abc.txt");//Not Valid
BufferedWriter bw = new BufferedWriter(new File("abc.txt"));//Not Valid
BufferedWriter bw = new BufferedWriter(new FileWriter("abc.txt"));//Valid
BufferedWriter bw = new BufferedWriter(new BufferedWriter(new FileWriter("abc.txt")));//Valid and called 2 level buffering

Methods of BufferedWriter:

write(int ch);
write(char[] ch);
write(String s);
flush();
close();
newLine();//To insert a line Separator

Writing to a file using BufferedWriter :

package com.fileDemo;

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

public class Demo {
	public static void main(String[] args) throws IOException {
		File f = new File("/home/tyson/Desktop/temp/file2");
		FileWriter fw = new FileWriter(f);
		BufferedWriter bw = new BufferedWriter(fw);
		bw.write("Hello");
		bw.write("World");
		bw.newLine();
		bw.write("You are writing a java program");
		bw.flush();
		bw.close();//No need to flush(), close() will call flush() internally
		//fw.close(); //file Writer object is closed automatically closed by buffered writer close method
	}
}

Note :

  • It is recommended to close buffered writer object and buffered writer object automatically closes the file writer.
  • It is not recommended to close fileWriter object.
  • flush() method of buffered writer is automatically closed while calling buffered writer’s close() method call

Leave a Comment