FileWriter in java

In previous post, we have seen InputStream and OutputStream. In this post, we will see how to write data to a text file with the help of  FileWriter in java.

FileWriter is a  character based classes unlike FileOutputStream which is used for writing byte based data.

In other words,  we should use FileWriter class when the data is in textual form.

Let’s understand it with example.


FileWriter is used to write a stream of characters to a file.

Constructor of the FileWriter:

Constructor Description
FileWriter(String file) Creates a new File.It gets the file name in the String.
FileWriter(File file) Creates a new File. It gets the file name in the File Object.

Example of FileWriter:

Output: Write successfully

FileWriter Methods:

  1. public void write(String text) : It writes String into FileWriter.
  2. public void write(char c) : It writes the char into FileWrite.
  3. public void write(char[] c) : It writes char array into FileWriter.
  4. public void flush() : It flushes the data of FileWriter.
  5. public void close() : It closes FileWriter.

Overwriting and Appending the File:

When creating FileWriter, we can decide if we want to overwrite the existing file with same name or we want to append the existing file with the data. For that , we have 2 provide a boolean parameter. Let’s see how to do this.

In the next post, we will see FileReader which is used for reading data from a text file.

Ask Question
Have any question or suggestion for us?Please feel free to post in Q&A Forum
InputStream and OutputStream in java
FileReader in java
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...

1 Response

  1. August 8, 2015

    […] For writing character oriented data, we can use FileWriter. […]