Writer

Writer is an abstract class for writing streams of characters in Java. It is the superclass for all classes that write character output, such as FileWriter, BufferedWriter, PrintWriter, etc.It is the character-based counterpart of OutputStream and handles text data efficiently across platforms with Unicode support.

Commonly Used Methods

Simple Program – Writing to a File Using FileWriter

Write a simple Java program that saves a welcome message to a file using Writer.

import java.io.*;

public class SimpleWriterDemo {
    public static void main(String[] args) {
        try {
            Writer writer = new FileWriter("welcome.txt");
            writer.write("Welcome to Java Writer Class!");
            writer.close();
            System.out.println("Message written to file.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output File: welcome.txt

Welcome to Java Writer Class!Code language: PHP (php)

Problem Statement:

LotusJavaPrince wants to develop a feature to store user bio-data in a text file. Mahesh suggests using BufferedWriter for performance and Writer hierarchy for flexibility.

import java.io.*;

public class BioDataWriter {
    public static void main(String[] args) {
        String[] bioData = {
            "Name: LotusJavaPrince",
            "Occupation: Software Architect",
            "Location: JavaPlanet",
            "Skills: Java, Spring, Design Patterns"
        };

        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter("bioData.txt"));

            for (String line : bioData) {
                writer.write(line);
                writer.newLine();
            }

            writer.close();
            System.out.println("Bio-data successfully written to file.");
        } catch (IOException e) {
            System.out.println("Error writing to file.");
            e.printStackTrace();
        }
    }
}

Output File: bioData.txt

Name: LotusJavaPrince
Occupation: Software Architect
Location: JavaPlanet
Skills: Java, Spring, Design PatternsCode language: HTTP (http)

The Writer class plays a central role in Java’s I/O system, particularly for writing character streams. As the abstract superclass of all character-output stream classes, it provides a flexible and extensible foundation for handling text data across various sources and formats.

Scroll to Top