FileWriter in Java

We use FileWriter to write characters to a file. FileWriter works much like the FileOutputStream except that a FileOutputStream is byte based, whereas a FileWriter is character based. One character may correspond to one or more bytes, depending on the character encoding scheme in use.

FileWriter extends OutputStreamWriter.

The FileWriter uses the default character encoding. If you want to specify a different character encoding scheme, don’t use a FileWriter. Use an OutputStreamWriter on a FileOutputStream instead. The OutputStreamWriter lets you specify the character encoding scheme to use when writing bytes to the underlying file.

Constructors

FileWriter in Java

Methods in FileWriter

Screen Shot 2020-03-25 at 8.57.56 PM

package com.java.io;

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

public class FileWriterExample {

    public static void main(String[] args) {
        FileWriter writer = null;
        try {
            writer = new FileWriter("/Test/TestFolder/test-file2.txt");
            writer.write("Writing Test data");
            writer.flush();
            System.out.println("Data written to File");
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException ioe) {

            }
        }
    }

}
Data written to File

Leave a Reply

Your email address will not be published. Required fields are marked *