Read and write data using FileReader & FileWriter

Q. Implementing FileReader and FileWriter class to read and write the data from file.

Answer:

The FileReader class creates a Reader that can be used to read the content of the file. The FileWriter class creates a Writer class that can be used to write the content of the file.

Here "test.txt" is a text file. We read the data from the text file by using FileReader class. The BufferdReader class is used to read the text from the input stream.

FileReaderFileWriter.java

import java.io.*;
class FileReaderFileWriter
{
     public static void main(String[] args)
     {
          String file = "test.txt"; //name of the text file
          String text = null;
          System.out.println("Content of the file: ");
          try
          {
               FileReader fileReader = new FileReader(file);
               BufferedReader bufferedReader = new BufferedReader(fileReader);
               while ((text = bufferedReader.readLine()) != null)
               {
                    System.out.println(text);
               }
               bufferedReader.close();
          }
          catch (FileNotFoundException ex)
          {
               ex.printStackTrace();
          }
          catch (IOException ex)
          {
               ex.printStackTrace();
          }
     }
}


Output:

filereader filewriter