dsa

Java OutputStream Class

In this tutorial, we will learn about the Java OutputStream and its methods with the help of an example.

This abstract class is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink. Applications that need to define a subclass of OutputStream must always provide at least a method that writes one byte of output.

Subclasses of OutputStream

    In order to use the functionality of OutputStream, we can use its subclasses. Some of them are:
  1. FileOutputStream
  2. ByteArrayOutputStream
  3. ObjectOutputStream
Subclasses of Java OutputStream are FileOutputStream, ByteArrayOutputStream and ObjectOutputStream.

Declaration :

      public abstract class OutputStream
      extends Object
      implements Closeable, Flushable

Class methods

Sr.No. Method & Description
1 void close()

This method closes this output stream and releases any system resources associated with this stream.

2 void flush()

This method flushes this output stream and forces any buffered output bytes to be written out.

3 void write(byte[] b)

This method writes b.length bytes from the specified byte array to this output stream.

4 void write(byte[] b, int off, int len)

This method writes len bytes from the specified byte array starting at offset off to this output stream.

5 abstract void write(int b)

This method writes the specified byte to this output stream.

Java Program explaining OutputStream Class methods :

iimport java.io.FileOutputStream;
import java.io.OutputStream;

public class Main {

    public static void main(String args[]) {
        String data = "This is a line of text inside the file.";

        try {
            OutputStream out = new FileOutputStream("output.txt");

            // Converts the string into bytes
            byte[] dataBytes = data.getBytes();

            // Writes data to the output stream
            out.write(dataBytes);
            System.out.println("Data is written to the file.");

            // Closes the output stream
            out.close();
        }

        catch (Exception e) {
            e.getStackTrace();
        }
    }
}

To write data to the output.txt file, we have implemented these methods.

output.write();      // To write data to the file
output.close();      // To close the output stream

When we run the program, the output.txt file is filled with the following content.

This is a line of text inside the file.