Use FileWriter class to write files in Java

The FileWriter class extends from the OutputStreamWriter class.

This class writes data to the stream character by character. You can create the required objects through the following construction methods.

  • Constructs a FileWriter object given a file name.
FileWriter(String fileName)
  • Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
FileWriter(String fileName, boolean append)

    · fileName: The file name of the data to be written.
    · append: If the append parameter is true, it means additional writing. If the append parameter is false, it means overwriting.

After successfully creating the FileWriter object, you can refer to the methods in the following list to manipulate the file.

  • Writes a string
public void write(String str)
  • Writes a portion of a string
public void write(String str, int off, int len)
  • Writes a single character
public void write(int c)
  • Writes an array of characters
public void write(char cbuf[])

Example

In the following example, the Java FileWriter class is used to write content to the Test.log file by appending.

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

public class TestFileWrite {
    public static void main(String[] args) throws IOException {
        File file = new File("Test.txt");

        if(!file.exists()) {
            file.createNewFile();
        }

        String fileContent = "This is the test content. \n";

        FileWriter fileWriter = new FileWriter(file.getName(), true);
        fileWriter.write(fileContent);
        fileWriter.close();

        System.out.println("Done.");
    }
}

Add a Comment

Your email address will not be published.