Java - BufferedReader and BufferedWriter example

Posted on November 8, 2016


BufferedReader and BufferedWriter use an internal buffer to store data while reading and writing, respectively. BufferedReader provides a new method readLine(), which reads a line and returns a String (without the line delimiter). 

The following example shows the use of BufferedReader and BufferedWriter.

BufferedReaderWriterExample.java

package com.boraji.tutorial.io;

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

/**
 * @author imssbora
 */
public class BufferedReaderWriterExample {
	public static void main(String[] args) {
		File file = new File("file.txt");
		
		/*Writing file using BufferedWriter*/
		FileWriter fileWriter = null;
		BufferedWriter bufferedWriter =null;
		try {
			fileWriter=new FileWriter(file);
			bufferedWriter =new BufferedWriter(fileWriter);
			bufferedWriter.write("This is an example \n");
			bufferedWriter.write("of using BufferedWriter and \n");
			bufferedWriter.write("BufferedReader.");
			bufferedWriter.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(fileWriter!=null){
					fileWriter.close();
				}
				if(bufferedWriter!=null){
					bufferedWriter.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		/*Reading file using BufferedReader*/
		FileReader fileReader=null;
		BufferedReader bufferedReader=null;
		try {
			fileReader =new FileReader(file);
			bufferedReader=new BufferedReader(fileReader);
			String line=null;
			while((line=bufferedReader.readLine())!=null){
				System.out.println(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(fileReader!=null){
					fileReader.close();
				}
				if(bufferedReader!=null){
					bufferedReader.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

Output (file.txt)

This is an example 
of using BufferedWriter and 
BufferedReader.