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)
  3. BufferedWriter never communicates directly with the file. It should be communicate through some writer object only.
Important methods of BufferedWriter Class
  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()

Example:

package com.java2learn.io;

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

public class BufferedWriterDemo {

	public static void main(String[] args) throws IOException {
		File f = new File("java2learn.txt");
		System.out.println(f.exists());
		FileWriter fw = new FileWriter(f);
		BufferedWriter bw = new BufferedWriter(fw);
		bw.write(97);
		bw.newLine();
		char[] ch1 = { 'a', 'b', 'c', 'd' };
		bw.write(ch1);
		bw.newLine();
		bw.write("TECH");
		bw.newLine();
		bw.write("software");
		bw.flush();
		bw.close();
	}
}

Note: When ever we r closing BufferedWriter ,automatically underlying FileWriter object will be closed.

BufferedReader

BufferedReader class can read character data from the file.

Constructors
  1. BufferedReader br = new BufferedReader(Reader r)
  2. BufferedReader br = new BufferedReader(Reader r, int buffersize)
  3. BufferedReader never communicates directly with the file. It should Communicate through some reader object only.
Important methods of BufferedReader Class
  1. int read()
  2. int read(char [] ch)
  3. String readLine();
    Reads the next line present in the file. If there is no nextline this method returns null.
  4. void close()

Example:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderDemo {

	public static void main(String[] args) throws IOException {
		FileReader fr = new FileReader("java2learn.txt");
		BufferedReader br = new BufferedReader(fr);
		String s = br.readLine();
		while (s != null) {
			System.out.println(s);
			s = br.readLine();
		}
		br.close();
	}
}

Note: When ever we are closing BufferedReader ,automatically underlying FileReader object will be closed.