Java FileWriter Class

The FileWriter class in Java is used to write data to a file. It belongs to the java.io package and extends the OutputStreamWriter class.

To create an instance of the FileWriter class, you need to pass the file name or the file object to the constructor. For example:

FileWriter writer = new FileWriter("filename.txt");

You can also specify whether you want to append to the file or overwrite it by passing a boolean value to the constructor. For example:

FileWriter writer = new FileWriter("filename.txt", true); // appends to the file

To write data to the file, you can use the write() method. There are several overloaded versions of the write() method that allow you to write different types of data, such as a string, a character array, or a portion of a string or character array.

For example, to write a string to the file, you can use the following code:

writer.write("Hello, world!");

When you’re finished writing to the file, you should close the FileWriter object using the close() method. This ensures that any buffered data is written to the file and any system resources used by the FileWriter object are released.

Here’s an example of using the FileWriter class to write some text to a file:

import java.io.*;

public class FileWriterExample {
    public static void main(String[] args) {
        try {
            FileWriter writer = new FileWriter("output.txt");
            writer.write("This is some text that we're writing to the file.\n");
            writer.write("We can write multiple lines using multiple calls to the write() method.\n");
            writer.close();
            System.out.println("Data written to file.");
        } catch (IOException e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}

Java FileWriter class declaration:

The declaration of the Java FileWriter class is as follows:

public class FileWriter extends OutputStreamWriter {
    public FileWriter(String fileName) throws IOException {
        super(new FileOutputStream(fileName));
    }
    
    public FileWriter(String fileName, boolean append) throws IOException {
        super(new FileOutputStream(fileName, append));
    }
    
    public FileWriter(File file) throws IOException {
        super(new FileOutputStream(file));
    }
    
    public FileWriter(File file, boolean append) throws IOException {
        super(new FileOutputStream(file, append));
    }
}

The FileWriter class extends the OutputStreamWriter class and provides constructors for creating a FileWriter object to write data to a file.

The first constructor takes a String argument that specifies the name of the file to be written. The constructor creates a FileOutputStream object with the specified file name and passes it to the superclass constructor. If the file does not exist, it will be created. If it already exists, its contents will be overwritten.

The second constructor is similar to the first one, but it takes a second boolean argument that specifies whether to append to the existing file or overwrite it. If the value of the append argument is true, the new data will be written to the end of the file. If it is false, the existing contents of the file will be overwritten.

The third and fourth constructors take a File object argument instead of a String argument. They create a FileOutputStream object with the specified file and pass it to the superclass constructor. The behavior of these constructors is otherwise the same as the first two constructors.

Constructors of FileWriter class:

The FileWriter class in Java has four constructors. Here are the details:

  1. public FileWriter(String fileName) throws IOException: This constructor creates a new FileWriter object that writes data to the file specified by the fileName parameter. If the file does not exist, it will be created. If it already exists, its contents will be overwritten.
  2. public FileWriter(String fileName, boolean append) throws IOException: This constructor is similar to the first one, but it takes a second boolean argument that specifies whether to append to the existing file or overwrite it. If the value of the append parameter is true, the new data will be written to the end of the file. If it is false, the existing contents of the file will be overwritten.
  3. public FileWriter(File file) throws IOException: This constructor creates a new FileWriter object that writes data to the file specified by the file parameter. If the file does not exist, it will be created. If it already exists, its contents will be overwritten.
  4. public FileWriter(File file, boolean append) throws IOException: This constructor is similar to the third one, but it takes a second boolean argument that specifies whether to append to the existing file or overwrite it. If the value of the append parameter is true, the new data will be written to the end of the file. If it is false, the existing contents of the file will be overwritten.

All four constructors can throw an IOException if an I/O error occurs while creating the file or opening it for writing. Therefore, it is recommended to surround the constructor call with a try-catch block or to declare the IOException in the method signature.

Methods of FileWriter class:

The FileWriter class in Java provides several methods for writing data to a file. Here are the details:

  1. public void write(int c) throws IOException: This method writes a single character specified by the c parameter to the file.
  2. public void write(char[] cbuf) throws IOException: This method writes an array of characters specified by the cbuf parameter to the file.
  3. public void write(char[] cbuf, int off, int len) throws IOException: This method writes a portion of an array of characters specified by the cbuf parameter to the file. The portion to be written is determined by the off parameter (the starting offset) and the len parameter (the number of characters to write).
  4. public void write(String str) throws IOException: This method writes a string specified by the str parameter to the file.
  5. public void write(String str, int off, int len) throws IOException: This method writes a portion of a string specified by the str parameter to the file. The portion to be written is determined by the off parameter (the starting offset) and the len parameter (the number of characters to write).
  6. public void flush() throws IOException: This method flushes any buffered output to the file.
  7. public void close() throws IOException: This method closes the FileWriter object and releases any system resources associated with it.

All these methods can throw an IOException if an I/O error occurs while writing to the file. Therefore, it is recommended to surround method calls with a try-catch block or to declare the IOException in the method signature.

Java FileWriter Example:

Here’s an example of using the Java FileWriter class to write data to a file:

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

public class FileWriterExample {
    public static void main(String[] args) {
        try {
            // Create a new FileWriter object with the file name "output.txt"
            FileWriter writer = new FileWriter("output.txt");

            // Write a string to the file
            writer.write("Hello, world!");

            // Flush the output to the file and close the writer
            writer.flush();
            writer.close();
        } catch (IOException e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}

In this example, we first create a new FileWriter object with the file name “output.txt”. We then use the write() method to write the string “Hello, world!” to the file. Finally, we call the flush() method to ensure that all output is written to the file and then close the writer using the close() method.

If an I/O error occurs while creating or writing to the file, the catch block will handle the IOException and print an error message to the console.