Open In App

File handling in Java using FileWriter and FileReader

Java FileWriter and FileReader classes are used to write and read data from text files (they are Character Stream classes). It is recommended not to use the FileInputStream and FileOutputStream classes if you have to read and write any textual information as these are Byte stream classes.
 

FileWriter
FileWriter is useful to create a file writing characters into it. 



Constructors: 

Methods: 



Reading and writing take place character by character, which increases the number of I/O operations and affects the performance of the system.BufferedWriter can be used along with FileWriter to improve the speed of execution.
The following program depicts how to create a text file using FileWriter
 




// Creating a text File using FileWriter
import java.io.FileWriter;
import java.io.IOException;
class CreateFile
{
    public static void main(String[] args) throws IOException
    {
        // Accept a string 
        String str = "File Handling in Java using "+
                " FileWriter and FileReader";
  
        // attach a file to FileWriter 
        FileWriter fw=new FileWriter("output.txt");
  
        // read character wise from string and write 
        // into FileWriter 
        for (int i = 0; i < str.length(); i++)
            fw.write(str.charAt(i));
  
        System.out.println("Writing successful");
        //close the file 
        fw.close();
    }
}

FileReader

FileReader is useful to read data in the form of characters from a ‘text’ file. 

Constructors: 

Methods: 

The following program depicts how to read from the ‘text’ file using FileReader
 




// Reading data from a file using FileReader
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
class ReadFile
{
    public static void main(String[] args) throws IOException
    {
        // variable declaration
        int ch;
  
        // check if File exists or not
        FileReader fr=null;
        try
        {
            fr = new FileReader("text");
        }
        catch (FileNotFoundException fe)
        {
            System.out.println("File not found");
        }
  
        // read from FileReader till the end of file
        while ((ch=fr.read())!=-1)
            System.out.print((char)ch);
  
        // close the file
        fr.close();
    }
}

 


Article Tags :