FileWriter Class in Java

In this article, we will understand how to use FileWriter class in Java. 

1. Introduction to FileWriter 

FileWriter is part of the package. It's a convenience class that facilitates writing character streams to files, bridging the gap between byte streams and character streams. It can create a new file, overwrite an existing file, or append to a file. 

2. Constructing a FileWriter 

Several constructors allow you to initialize a FileWriter object, giving you flexibility based on your requirements:

FileWriter writer1 = new FileWriter("path_to_file.txt"); // Creates or overwrites
FileWriter writer2 = new FileWriter("path_to_file.txt", true); // Appends to file if it exists

3. Writing to a File 

FileWriter provides methods to write characters, character arrays, or strings to a file:

writer1.write(65);  // Writes the character 'A' 
writer1.write("Hello World");
char[] charData = {'J', 'a', 'v', 'a'};

4. Advantages of FileWriter 

Automatic Encoding: Translates character data into bytes using the default or specified charset, which is usually the platform's default charset. 

Ease of Use: High-level operations make writing text data straightforward. 

5. Considerations Charset Considerations

By default, FileWriter uses the system's default charset. This might not always be desired. For precise control over encoding, use OutputStreamWriter. 

Always Close: It's vital to close the writer after operations to release resources and ensure that all data is written to the file. 

6. Flushing and Closing 

Data is sometimes buffered and not immediately written to the destination. 

Ensure you flush the stream:


Use try-with-resources for automatic closure:

try (FileWriter writer = new FileWriter("path_to_file.txt")) {
    // ... operations

7. When to Use FileWriter?

Text Data Writing: Choose FileWriter when your primary goal is to write character-based (text) data to files. It encodes characters into bytes using the system's default character encoding, simplifying the process of saving textual data. 

Simplified File Writing: If you're looking for a direct and uncomplicated way to write character data to a file without additional configuration or buffering, FileWriter is an excellent option. It bridges the gap between in-memory character data and file-based storage. 

Foundation for Buffered Writing: FileWriter seamlessly integrates with BufferedWriter, allowing for more efficient and large-scale writing operations. When combined, they offer improved performance and additional methods, such as the ability to write whole lines in a single call.

8. Complete Code

let's compile all the steps related to the FileWriter class into a single FileWriterExample class. This class will demonstrate creating a FileWriter, writing to a file named output.txt, and displaying a confirmation of the written data:


public class FileWriterExample {

    public static void main(String[] args) {
        // File name
        String filename = "output.txt";

        // Data to be written
        String content = "Hello from FileWriter!\nJava I/O is powerful and flexible.";

        // Using FileWriter to write to the file
        try (FileWriter writer = new FileWriter(filename)) {

            // Writing string content to the file

            // Printing confirmation
            System.out.println("Data written to " + filename + " successfully!");

        } catch (IOException e) {
            System.out.println("An error occurred: " + e.getMessage());

// Expected Output:
// Data written to output.txt successfully!

To see the actual written content, you'd have to open the output.txt file. If the program runs without errors, the content written to the file should match the content string.

Related Java I/O Classes