How to use FileWriter and FileReaderClass in JAVA

FileWriter class

The FileWriter class is used to write the data to a file of a given file name or full path string. The FileWriter class will throw an Exception named IOException or SecurityException so you need to handle the Exception in your code.

Creation of a FileWriter is not dependent on the file already existing. A FileWriter will create the file before opening it for output when you create the object. In the case where you attempt to open a read-only file, an IOException will be thrown.

There are commonly used constructor :

FileWriter(String path of file)

In this constructor you give the path of a specific directory like as "D:\abhishekDubey\java".

FileWriter(String pathoffile, boolean append)

In this constructor there are two arguments, first pathofthefile and second append if append is true then ouput is appended to the end of the file.

FileWriter(File fileobject)

In this constructor you can give the direct File type object that describes the file.


The following example shows how a string can be written to a file with the help of the FileWriterclass; this program first checks the current directory to determine if the particular file is available or not; if not then it creates a new file before writing the data to the file.

class MyFileWriter
public static void main (String arg[]) throws IOException
// first we make the object of FileWriter class
FileWriter fw=new FileWriter("abhishek.txt");
//this is a string and using write in "abhishek.txt" file
String s="this article complete for all of you for learning purpose";
// toCharArray() is method to convert a string in a character array
char ch[]=s.toCharArray();
for(int i=0;i<ch.length;i++)





"FileReader" class in java

The "FileReader" class is used for reading the data (contents) of a file. This class is a child class of the Reader class; their commonly used constructor is a follows:

Either can throw a FileNotFoundException or IOException.

FileReader(String path)

This type constructor takes the path =full path of the file which file you want to read.

FileReader(File objectfile)

In this constructor you can give the direct File type object that describe the file.


The following program shows how we can read a file's content from a given file.

This first checks that the particular file exists or not; if not then it will throw an exception (that is FileNotFoundException).


class MyFileReader
public static void main(String arg[]) throws IOException
int i= 0;
FileReader fr=new FileReader("abhishek.txt");




This article provided the help showing how you can implement FileReader and FileWriter class in your program for raeding and writing data from a file and its not a particular string is written to the file; you can write any type of data in a file.

Up Next
    Ebook Download
    View all
    View all