FileReader and FileWriter in Java

FileReader

The FileReader class is used to read the data from a file as characters. It is recommended to use FileReader to read the data from text file. It extends the InputStreamReader class.

FileReader Constructors

ConstructorsDescription
FileReader( File file)Creates a new FileReader and given the file to read from.
FileReader(FileDescriptor fd)Creates a new file with FileDescriptor to read from.
FileReader(String filename)Creates a new FileReader, given the name of the file to read from.

Example: Implementing FileReader class to read the data from file.

import java.io.*;
public class FileReaderDemo
{
    public static void main(String args[])throws FileNotFoundException, IOException
    {
         FileReader fr = new FileReader("abc.txt");
         int i;
         System.out.println("ASCII value of the character:");
         while((i=fr.read()) != -1)
         {
             System.out.print(i+" : ");
              System.out.println ((char)i);
         }
     }
}


Output:
ASCII value of the character:
65 : A
66 : B
67 : C
97 : a
98 : b
99 : c

FileWriter

The FileWriter class is used o write the data to a file as characters. It extends the OutputStreamWriter class.

FileWriter Constructors

ConstructorsDescription
FileWriter( File file)It constructs a FileWriter object given a file object.
FileWriter(FileDescriptor fd)It creates a FileWriter object with file descriptor.
FileWriter(String filename)Creates a FileWriter object with specified file name.
FileWriter(File file, boolean append)Creates a FileWriter object given by a file object.
FileWriter(String filename, boolean append)Creates the FileWriter object given a file name.

Example: Implementing FileWriter class to write the data on file.

import java.io.*;
public class FileWriterDemo
{
    public static void main(String args[]) throws IOException
    {
        FileWriter fw = new FileWriter("abc.txt");
        char c = 'a';
        fw.write(c);
        System.out.println("Character "+c+" is write in file");
        fw.close();
    }
}


Output:
Character a is write in file