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.
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.
The following declaration shows how the FileWriter class is defined:
The FileWriter class provides constructors to create and write data to files.
This constructor creates a new file using the specified file name in string format.
Syntax:
Here is the syntax of this constructor:
This constructor creates a new file using a File object.
Syntax:
Here is the syntax of this constructor:
The following example demonstrates how the constructors of the FileWriter class are used.
The FileWriter class provides methods to write character data into a file.
| Method | Description |
|---|---|
| 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. |
The following examples demonstrate how to write data to a file using the FileWriter class.
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.
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
We request you to subscribe our newsletter for upcoming updates.