OutputStream

OutputStream is an abstract class for writing raw bytes to a destination (like a file, memory buffer, socket, etc.). Subclasses handle actual implementations, such as FileOutputStream, BufferedOutputStream, etc.

Commonly Used Methods

Simple Program – Write Data to File

LotusJavaPrince wants to write the string “Hello, Mahesh!” to a file using FileOutputStream.

import java.io.FileOutputStream;
import java.io.IOException;

public class SimpleOutputStreamExample {
    public static void main(String[] args) {
        String message = "Hello, Mahesh!";
        try (FileOutputStream fos = new FileOutputStream("greeting.txt")) {
            fos.write(message.getBytes()); // Convert string to bytes and write
            System.out.println("Message written to file.");
        } catch (IOException e) {
            System.err.println("Error writing to file: " + e.getMessage());
        }
    }
}

Output:

A file named greeting.txt will contain:

Hello, Mahesh!

Problem Statement:

LotusJavaPrince is building a logging system. Every log message (INFO, WARNING, ERROR) must be written to a file using OutputStream. The log should append messages for every run.

import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;

public class Logger {
    private static final String LOG_FILE = "system.log";

    public static void log(String level, String message) {
        String timestamp = LocalDateTime.now().toString();
        String logEntry = timestamp + " [" + level.toUpperCase() + "] " + message + "\n";

        try (FileOutputStream fos = new FileOutputStream(LOG_FILE, true)) {
            fos.write(logEntry.getBytes());
            fos.flush();
        } catch (IOException e) {
            System.err.println("Logging failed: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        log("INFO", "System started by LotusJavaPrince");
        log("WARNING", "Mahesh noticed high CPU usage");
        log("ERROR", "Database connection lost");
    }
}

Output in system.log:

2025-05-30T12:45:32.789 [INFO] System started by LotusJavaPrince
2025-05-30T12:45:32.790 [WARNING] Mahesh noticed high CPU usage
2025-05-30T12:45:32.791 [ERROR] Database connection lostCode language: CSS (css)

In the above output each execution appends new logs.

OutputStream is the superclass for writing byte-based output.

  • It cannot be instantiated directly – use subclasses like FileOutputStream.
  • Useful for writing to files, sockets, buffers, etc.
  • Works at low-level byte granularity, suitable for binary data.
Scroll to Top