FileWriter

FileWriter is a character stream class used to write character data (text) to a file. It is part of the java.io package and is used for writing text files.

Commonly Used Constructors and Methods

Simple Program

Mahesh wants to write a greeting message to a file named greeting.txt using FileWriter.

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

public class FileWriterExample {
    public static void main(String[] args) {
        try (FileWriter fw = new FileWriter("greeting.txt")) {
            fw.write("Hello, LotusJavaPrince!");
            System.out.println("Message written successfully.");
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Content of greeting.txt after execution:

Hello, LotusJavaPrince!

Output:

Message written successfully.

Problem Statement:

LotusJavaPrince wants to create a log system that writes a list of tasks performed into a file log.txt. The system should:

  • Append tasks instead of overwriting.
  • Record the timestamp and task description.
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class TaskLogger {
    public static void main(String[] args) {
        String[] tasks = {
            "Started banking module.",
            "User authenticated.",
            "Transaction processed.",
            "Session terminated."
        };

        try (FileWriter fw = new FileWriter("log.txt", true)) { // append mode
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            for (String task : tasks) {
                String log = dtf.format(LocalDateTime.now()) + " - " + task + "\n";
                fw.write(log);
            }
            System.out.println("Log written successfully.");
        } catch (IOException e) {
            System.out.println("Error writing log: " + e.getMessage());
        }
    }
}

Sample Content of log.txt after multiple executions:

2025-05-30 10:42:18 - Started banking module.
2025-05-30 10:42:18 - User authenticated.
2025-05-30 10:42:18 - Transaction processed.
2025-05-30 10:42:18 - Session terminated.Code language: CSS (css)

FileWriter is perfect for writing text data to files in a character-oriented way.

  • It is often used with BufferedWriter for performance optimization.
  • Use the append constructor (FileWriter(String, boolean)) to preserve existing file content.
  • It’s not suitable for binary files (images, PDFs)—use FileOutputStream for that.
Scroll to Top