OutputStreamWriter

OutputStreamWriter is a bridge from character streams to byte streams. It encodes character data into bytes using a specified charset and writes them to an underlying byte stream (like FileOutputStream,Socket.getOutputStream()).

It is typically used when you need to write character data to a destination that only supports byte streams.

Commonly Used Constructors and Methods

Simple Program: Writing Characters to File

Write a string to a file using OutputStreamWriter and ensure proper character encoding (UTF-8).

import java.io.*;

public class OutputStreamWriterSimpleDemo {
    public static void main(String[] args) {
        try (OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("output_utf8.txt"), "UTF-8")) {
            osw.write("Hello from OutputStreamWriter!\n");
            osw.write("This supports UTF-8 encoding.");
            System.out.println("Data written successfully to output_utf8.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Problem Statement:

LotusJavaPrince is developing a logging system for an international banking application. Mahesh suggests logging messages in different languages (e.g., English, Hindi, Japanese) to a UTF-8 encoded file using OutputStreamWriter.

import java.io.*;

public class MultilingualLogger {
    public static void main(String[] args) {
        String[] messages = {
            "English: Welcome to the system.",
            "Hindi: स्वागत है सिस्टम में।",
            "Japanese: システムへようこそ。"
        };

        try (OutputStreamWriter writer = new OutputStreamWriter(
                new FileOutputStream("multilingual_log.txt", true), "UTF-8")) {

            for (String msg : messages) {
                writer.write(msg + "\n");
            }

            System.out.println("Multilingual log written successfully.");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The OutputStreamWriter class is a powerful and essential tool in Java’s I/O framework for writing character data to byte-oriented streams. It acts as a bridge between character streams and byte streams, making it indispensable for applications that need to handle internationalization or write character data to files, sockets, or other byte-based outputs.

Scroll to Top