FileReader and FileWriter in Java

Learn about FileReader and FileWriter in Java, Java FileWriter and FileReader classes are used to write and read data from text files. These are character-oriented classes, used for file handling in java.

They belong to JDK 1.1 . Let’s understand the both classes one by one.


Use of FileReader and FileWriter in Java

FileWriter in Java:

Java FileWriter class is used to write character-oriented data to the file.There are different constructors of FileWriter.

FileWriter(File file) : Creates a new file.  Accepts File Object .


FileWriter(File file, boolean append) : Accepts File object and Boolean operator as true or false for append mode.


FileWriter(String fileName) : File path as String.


Creation of a FileWriter is not dependent on the file already existing. 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.


Methods of FileWriter class – Let’s see the methods of FileWriter class.

  • public void write(String text) – It writes the String into file writer.
  • public void flush() – Flushes the data of FileWriter.
  • public void close() – Close the file writer.

Let’s understand this with an easy example. In this example, we are creating a file inside our local machine and then writing text into it.


FileReader Class in Java:

Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class.FileReader reads character stream. The constructors are as below.

  • FileReader(File file) : Accepts File object .
  • FileReader(String fileName) : Accepts file path as string.

FileReader can throw the exception a FileNotFoundException.


Methods of the FileReader – Let’s see the methods of FileReader class.

  • public int read() – It returns a character in ASCII form. It returns -1 at the end of the file.
  • public void close() – To close file reader.

Let’s understand this with an easy example.

The above code will read the target file if present otherwise throws the error .

You can try the above code in your local machine as well. It’s highly recommended to practice the code.


Selenium Tutorial:

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.


0 Comment

Leave a Reply