Home » Core Java » io » FileWriter » Java FileWriter Example

About Aldo Ziflaj

Aldo Ziflaj
Aldo is a student of Computer Engineering and a programming addict. He spares his free time coding, whether mobile, web, or desktop programming. He is also one of the co-founders of Things Lab.

Java FileWriter Example

Last updated Jan. 21, 2019

In this example we will discuss about the FileWriter class and how to use it to write streams of characters. Whether or not a file is available or may be created depends upon the underlying platform. Some platforms, in particular, allow a file to be opened for writing by only one FileWriter (or other file-writing object) at a time. In such situations the constructors in this class will fail if the file involved is already open.

FileWriter extends OutputStreamWriter, which is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform’s default charset may be accepted.

The FileWriter class exists since JDK1.1.

The structure of FileWriter


  • FileWriter(File file)Constructs a FileWriter object given a File object.
  • FileWriter(File file, boolean append)Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
  • FileWriter(FileDescriptor fd)Constructs a FileWriter object associated with a file descriptor.
  • FileWriter(String fileName)Constructs a FileWriter object given a file name.
  • FileWriter(String fileName, boolean append)Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.

Overwriting vs. Appending the File

The constructor FileWriter(File file, boolean append) has a boolean flag as a second parameter and work as follows:

  • Overwrite

If append is set to false then it wil create a FileWriter that will overwrite any content that is currently in that file

  • Append

If append is set to true then it wil create a FileWriter that appends to an existing file.

The FileWriter in Java

To show a basic usage of FileWriter I created this class called SimpleFileWriterExample:

package com.javacodegeeks.examples;

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

public class SimpleFileWriterExample {
	public static void main(String[] args) {
		String name = "John Doe";
		int age = 44;
		double temp = 26.9;
		FileWriter fw;
		try {
			fw = new FileWriter(new File("mytextfile.txt"));
			fw.write(String.format("My name is %s.",name));
			fw.write(System.lineSeparator()); //new line
			fw.write(String.format("I am %d years old.",age));
			fw.write(System.lineSeparator()); //new line
			fw.write(String.format("Today's temperature is %.2f.",temp));
			fw.write(System.lineSeparator()); //new line
		} catch (IOException ex) {


What I just did was creating an instance of FileWriter, passing a File as a parameter, and then I started writing on it, using System.lineSeparator() to create new lines into the file. In the end of this, I closed the FileWriter instance, using the close() method, inherited from the OutputStreamWriter.

If you open the file, you will see this:

My name is John Doe.
I am 44 years old. 
Today's temperature is 26.90. 

Difference between flush and close

  • flush() writes the content of the buffer to the destination and makes the buffer empty for further data to store but it does not closes the stream permanently. That means you can still write some more data to the stream.
  • close() closes the stream permanently. If you want to write some data further, then you have to reopen the stream again and append the data with the existing ones.

A better usage of FileWriter

To show a more practical usage of the FileWriter in Java, I created a simple Logger, which can be used to log data into a text file. So, create a class called Logger into the mylogger package, and put this code into it:

package com.javacodegeeks.examples.mylogger;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

public class Logger {
	private File logFile;
	public Logger() {
	public Logger(String fileName) {
		logFile = new File(fileName);
	public Logger(File f) {
		logFile = f;
	public void log(String s) {
		try {
			FileWriter fw = new FileWriter(this.logFile,true);
			String date = new Date().toString();
			fw.write(date+" : "+s);
		} catch (IOException ex) {
			System.err.println("Couldn't log this: "+s);


This class creates a Logger object which you can use to log into a file by calling the log() method. To test this, create a new class, called Main, with this source code:

package com.javacodegeeks.examples.mylogger;

import java.io.File;

public class Main {

	public static void main(String[] args) {
		Logger log1 = new Logger("file1.txt");
		File f = new File("file2.txt");
		Logger log2 = new Logger(f);
		log1.log("This is written in the first file");
		log2.log("This is written in the second file");
		log1.log("This is appended to the first file");
		log2.log("This is appended to the second file");

Here I just tested the two different constructors and logged two messages into two different files. The output in them is this:

Tue Aug 26 16:21:06 PDT 2014 : This is written in the first file
Tue Aug 26 16:21:06 PDT 2014 : This is appended to the first file

And this:

Tue Aug 26 16:21:06 PDT 2014 : This is written in the second file
Tue Aug 26 16:21:06 PDT 2014 : This is appended to the second file

More about FileWriter in Java

FileWriter’s performance can be improved with BufferedWriter. BufferedWriter writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings. BufferedWriter extends Writer, which is an abstract class for writing to character streams. The only methods that a subclass must implement are
write(char[], int, int), flush(), and close(). Most subclasses, however, will override some of the methods defined here in order to provide higher efficiency, additional functionality, or both.

All of the constructors of FileWriter throw an IOException if the named file exists but is a directory rather than a regular file, or it does not exist but cannot be created, or it cannot be opened for any other reason.

Download Code

You can download the full source code of this example here : FileWriterExample
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area


Leave a Reply

Notify of