FileWriter Class

FileWriter Class

In this tutorial, we are going to discuss about FileWriter class in Java. This class can be used for writing character data to the file. It is not recommended to use the FileOutputStream class if we have to write any textual information as these are Byte stream classes.

FileWriter class in java is used to create files, and characters can be written into the created file; output stream class is the base class of FileWriter class as it is being inherited from it, and the assumption made by the constructor of this class is that default character encoding and default byte buffer size are permitted if these values are to be specified by us an output stream writer must be constructed on a file output stream.

FileWriter Class

Here’s an overview of the FileWriter class:

Constructors
FileWriter fw = new FileWriter(String fname)
FileWriter fw = new FileWriter(File f); 

The above 2 constructors creates a file object to write character data to the file. If the file already contains some data it will overwrite with the new data. Instead of overriding if you have to perform append then we have to use the following constructors.

FileWriter fw = new FileWriter(String name, boolean append);
FileWriter fw = new FileWriter(File f, boolean append); 

If the underlying physical file is not already available then the above constructors will create the required file also.

Important methods

1. void write(int ch) throws IOException

For writing single character to the file.

2. void write(String s)throws IOException.

3. void write(char [] ch) throws IOException.

4. void flush()

To guaranteed that the last character of the data should be required to the file.

package com.ashok.files;

import java.io.File;
import java.io.FileWriter;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class MyFile {
   public static void main(String arg[]) throws Exception {
      File f = new File("Ashok.txt");
      System.out.println(f.exists());
      FileWriter fw = new FileWriter(f, true);
      System.out.println(f.exists());
      fw.write(97);
      fw.write("Hai\nHow are you\n");
      char[] ch1 = { 'a', 'b', 'c' };
      fw.write(ch1);
      fw.flush();
      fw.close();
   }
}

Output

true
true

In Ashok.txt 
1st time
aHai
How are you
abc

2ndtime
aHai
How are you
abcaHai
How are you
abc

That’s all about the FileWriter Class in java. If you have any queries or feedback, please write us email at contact@waytoeasylearn.com. Enjoy learning, Enjoy Java.!!

FileWriter Class
Scroll to top