Java FileWriter Class


In Java, the FileWriter class is a commonly used utility to write data to files. It is part of the java.io package and is used for writing character data to files. In this blog post, we will explore the features of the FileWriter class, how to use it, and provide practical code examples to demonstrate its usage.


What is Java FileWriter Class?

The FileWriter class is a subclass of OutputStreamWriter and provides an easy way to write character data to files. This class is intended for writing text files, and it works with character streams, making it suitable for working with data in text format like .txt, .csv, and .xml files.

Key Features of FileWriter:

  • Writes character data to files.
  • Supports writing text-based files like .txt, .csv, and .json.
  • Automatically encodes the data using the default character encoding (usually UTF-8).
  • Can append to existing files without overwriting them.

Syntax of FileWriter Class

The FileWriter class offers two commonly used constructors:

FileWriter(String fileName) throws IOException

This constructor creates a FileWriter object to write to the specified file.

FileWriter(String fileName, boolean append) throws IOException

This constructor allows you to specify whether you want to append data to the file or overwrite it. If the append parameter is set to true, data will be appended to the end of the file. Otherwise, the file will be overwritten.


How to Use the FileWriter Class

To write data to a file, you create a FileWriter object and use its methods like write() or append().

Example 1: Writing to a File

In this example, we'll create a FileWriter object to write text data into a file named example.txt.

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

public class FileWriterExample {
    public static void main(String[] args) {
        FileWriter writer = null;

        try {
            // Create a FileWriter object to write to the file
            writer = new FileWriter("example.txt");

            // Write data to the file
            writer.write("Hello, World!\n");
            writer.write("This is an example of using FileWriter in Java.");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // Close the FileWriter
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Explanation:

  • The FileWriter object is created, and we specify the file name (example.txt).
  • The write() method writes data to the file. If the file doesn't exist, Java will create it.
  • The finally block ensures that the FileWriter is closed after use to prevent resource leaks.

Writing Data Using FileWriter with Append Mode

In some cases, you might want to add new content to an existing file without overwriting it. You can do this by using the append parameter when creating the FileWriter object.

Example 2: Appending Data to a File

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

public class FileWriterAppendExample {
    public static void main(String[] args) {
        FileWriter writer = null;

        try {
            // Create a FileWriter object in append mode
            writer = new FileWriter("example.txt", true);

            // Append data to the file
            writer.write("\nThis is new content being added to the file.");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // Close the FileWriter
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Explanation:

  • We pass true as the second argument to the FileWriter constructor, which opens the file in append mode.
  • Any new data written will be added at the end of the file, rather than overwriting its content.

Using FileWriter with BufferedWriter

While FileWriter works well for small file writing operations, when dealing with larger files, it is more efficient to combine it with BufferedWriter. BufferedWriter writes data to a file in large chunks, which significantly improves performance for writing large amounts of text.

Example 3: Writing to a File Using BufferedWriter

import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

public class BufferedWriterExample {
    public static void main(String[] args) {
        FileWriter writer = null;
        BufferedWriter bufferedWriter = null;

        try {
            // Create FileWriter and BufferedWriter objects
            writer = new FileWriter("example.txt");
            bufferedWriter = new BufferedWriter(writer);

            // Write data to the file using BufferedWriter
            bufferedWriter.write("Hello, this is an efficient way to write to a file in Java.");
            bufferedWriter.newLine();
            bufferedWriter.write("BufferedWriter helps to write data in chunks for better performance.");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // Close BufferedWriter and FileWriter
                if (bufferedWriter != null) {
                    bufferedWriter.close();
                }
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Explanation:

  • In this example, we use BufferedWriter in conjunction with FileWriter to efficiently write to the file.
  • The newLine() method adds a newline after the text to ensure proper formatting in the file.

FileWriter Exception Handling

The FileWriter class can throw an IOException if there are issues with the file writing process, such as permission issues or file not being found. Handling exceptions properly is essential for creating robust file-writing applications.

Example 4: Handling IOExceptions

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

public class FileWriterWithExceptionHandling {
    public static void main(String[] args) {
        try {
            // Attempt to write to a file
            FileWriter writer = new FileWriter("nonexistent_folder/example.txt");
            writer.write("This will fail because the folder doesn't exist.");
            writer.close();
        } catch (IOException e) {
            System.out.println("Error writing to file: " + e.getMessage());
        }
    }
}

Explanation:

  • If the directory doesn't exist or there are permission issues, IOException will be thrown.
  • The catch block catches this exception and prints an error message.

Best Practices When Using FileWriter

  1. Always Close Resources: Use the close() method to close the FileWriter and free up resources. You can also use try-with-resources to simplify this process.
  2. Use BufferedWriter for Large Files: When writing large files, always use BufferedWriter to improve performance.
  3. Handle Exceptions: Always handle IOException to avoid unexpected crashes, especially when dealing with file paths or permissions.
  4. Use Append Mode: If you need to add content to an existing file without overwriting it, use the append mode (true in the constructor).