FileReader and FileWriter in Java


The FileReader and FileWriter classes are used to read data from files and write data to the files.

FileReader

The FileReader class, as the name implies, has the capability to read data from files. We can create FileReader objects in 2 ways. These are:

  • FileReader(String filePath)
  • FileReader(File fileObj)

The following example demonstrates how to read the data from the file:

 import java.io.BufferedReader;
 import java.io.FileNotFoundException;
 import java.io.FileReader;
 import java.io.IOException;
 
 public class FileReadEx {
 	public static void main(String[] args) {
 		try {
 			FileReader fr = new FileReader("src\\filedemo.txt");
 			BufferedReader br  = new BufferedReader(fr);
 			String line;
 			while ((line = br.readLine())!=null) {
 				System.out.println(line);
 			}
 		} catch (FileNotFoundException e) {
 			System.out.println("File is not available for Read");
 			e.printStackTrace();
 		}
 		catch (IOException e) {
 			System.out.println("there is a error while reading the file");
 			e.printStackTrace();
 		}
 	}
 }

The previous example reads the file line by line.

FileWriter

The FileWriter class is used to write data to a file. We can create the FileWriter Objects by using the following methods:

  • FileWriter(String filePath)
  • FileWriter(String filePath, boolean append) //appends data to the file, instead of overwriting the data
  • FileWriter(File fileObj)

The following example demonstrates how to write the data to the file:

 import java.io.BufferedWriter;
 import java.io.FileNotFoundException;
 import java.io.FileWriter;
 import java.io.IOException;
 
 
 public class WriteToFileEX {
 	
 	public static void main(String[] args) {
 		FileWriter fw =null;
 		BufferedWriter bw =null;
 		try {
 			String dataToWrite="This is test the file Writing \n"+
 		                       "another line for writing";
 					
 			fw = new FileWriter("src\\fileDemo.txt");
 			bw= new BufferedWriter(fw);
 			bw.write(dataToWrite);
 			bw.close();
 			fw.close();
 		} catch (FileNotFoundException e) {
 			System.out.println("File is not available for write");
 			e.printStackTrace();
 		}
 		catch (IOException e) {
 			System.out.println("there is a error while writing to the file");
 			e.printStackTrace();
 		}
 	}
 }

After the execution of the class example above, the file will be created with the data written in it.