Java - FileReader and FileWriter example

Posted on November 8, 2016


FileReader and FileWriter are convenience classes for reading and writing character files respectively. Both FileReader and FileWriter classes use system’s default encoding.

The following example shows the usage of the FileReader and FileWriter.

FileReaderWriterExample.java

package com.boraji.tutorial.io;

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

/**
 * @author imssbora
 */
public class FileReaderWriterExample {
	public static void main(String[] args) {
		File file = new File("file.txt");

		/* Writing File Using FileWriter */
		FileWriter fileWriter = null;
		try {
			fileWriter = new FileWriter(file);
			fileWriter.write("This is an example of using");
			fileWriter.write(" FileReader and ");
			fileWriter.write(" FileWriter. ");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fileWriter != null) {
					fileWriter.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		/* Reading File Using FileReader */
		FileReader fileReader = null;
		try {
			fileReader=new FileReader(file);
			char ch[]=new char[20];
			int i=0;
			while((i=fileReader.read(ch))!=-1){
				System.out.println(new String(ch,0,i));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if (fileReader != null) {
					fileReader.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

Output (file.txt)

This is an example o
f using FileReader a
nd  FileWriter.