Site icon LinuxCommands.site

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.

FileWriter(String fileName)
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.

public void write(String str)
public void write(String str, int off, int len)
public void write(int c)
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.");
    }
}

Exit mobile version