BufferedWriter Class

BufferedWriter

This can be used for writing character data to the file.

Constructors
1. BufferedWriter bw = new BufferedWriter(writer w)
2. BufferedWriter bw = new BufferedWriter(writer r, int size) 

BufferedWriter never communicates directly with the file. It should Communicate through some writer object only.

BufferedWriter bw = new BufferedWriter(β€œashok.txt”); // Invalid
BufferedWriter bw = new BufferedWriter(new File(β€œashok.txt”)); // Invalid
BufferedWriter bw = new BufferedWriter(new FileWriter(β€œashok.txt”)); // Valid
BufferedWriter bw = new BufferedWriter(new BufferedWriter(new FileWriter(β€œashok.txt”))); // Valid 
Important methods
1. void write(int ch) thorows IOException
2. void write(String s) throws IOException
3. void write(char[] ch) throws IOException
4. void newLine()
For inserting a new line character.
5. void flush()
6. void close() 

E.g

package com.ashok.files;

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

public class MyFile {
   public static void main(String arg[]) throws Exception {
      File f = new File("ashok.txt");
      System.out.println(f.exists());
      FileWriter fw = new FileWriter(f);
      BufferedWriter bw = new BufferedWriter(fw);
      bw.write(97);
      bw.newLine();
      char [] ch = {'a','b','c','d'};
      bw.write(ch);
      bw.newLine();
      bw.write("Ashok");
      bw.newLine();
      bw.write("Waytoeasylearn");
      bw.flush();
      bw.close();
   }
}
Output
true

In ashok.txt
a
abcd
Ashok
Waytoeasylearn

Note

When ever we are closing BufferedWriter, automatically underlying FileWriter object will be closed.

BufferedWriter Class


Scroll to top