Java FileWriter Class

Last Updated : 27 Jan 2026

The FileWriter class in Java is used to write character-oriented data directly into a file.

In this chapter, we will learn what the FileWriter class is, why it is used, its declaration, constructors, important methods, and how to write character data to files using examples.

What is FileWriter Class in Java?

The FileWriter class is a character-based output stream that is used to write text data to a file, and it is commonly used for file handling in Java.

Unlike the FileOutputStream class, FileWriter allows writing strings and characters directly without converting them into byte arrays, which makes it easier to use for character-oriented data.

Java FileWriter Class Declaration

The following declaration shows how the FileWriter class is defined:

Constructors of FileWriter Class

The FileWriter class provides constructors to create and write data to files.

1. FileWriter(String file)

This constructor creates a new file using the specified file name in string format.

Syntax:

Here is the syntax of this constructor:

2. FileWriter(File file)

This constructor creates a new file using a File object.

Syntax:

Here is the syntax of this constructor:

Example of FileWriter Class Constructors

The following example demonstrates how the constructors of the FileWriter class are used.

Methods of FileWriter Class

The FileWriter class provides methods to write character data into a file.

MethodDescription
void write(String text)It is used to write the string into FileWriter.
void write(char c)It is used to write the char into FileWriter.
void write(char[] c)It is used to write char array into FileWriter.
void flush()It is used to flushes the data of FileWriter.
void close()It is used to close the FileWriter.

Examples of Java FileWriter Class

The following examples demonstrate how to write data to a file using the FileWriter class.

Example 1: Writing a String to a File

This example demonstrates how to write a string directly into a file using the FileWriter class.

Output:

Success...

File Content (testout.txt):

Welcome to TpointTech.

Example 2: Writing Character Array to a File

This example demonstrates how to write a character array into a file using the FileWriter class.

Output:

Characters written successfully

File Content (testout2.txt):

Java IO