BufferedOutputStream Class in Java

The BufferedOutputStream class in Java is part of the java.io package. It is used to write data to an output stream with a buffer. This class provides a more efficient way of writing data by reducing the number of I/O operations through buffering the output. It is essential for improving performance when writing large amounts of data to an output stream.

Table of Contents

  1. Introduction
  2. Creating a BufferedOutputStream
  3. Writing Data to a BufferedOutputStream
  4. Flushing the Stream
  5. Closing the Stream
  6. Complete Example
  7. Conclusion

Introduction

The BufferedOutputStream class is a subclass of FilterOutputStream and is designed to add buffering to output streams. Buffering can improve the performance of I/O operations by reducing the number of physical writes to the underlying output source, such as a file or network connection. The BufferedOutputStream writes chunks of data to a buffer, which is then written to the output stream as needed.

Creating a BufferedOutputStream

To create a BufferedOutputStream, you need to wrap it around another output stream, such as a FileOutputStream. You can also specify the size of the buffer, although a default size is provided if you do not specify one.

Example

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class BufferedOutputStreamExample {
    public static void main(String[] args) {
        try {
            // Creating BufferedOutputStream using FileOutputStream
            FileOutputStream fos = new FileOutputStream("example.txt");
            BufferedOutputStream bos = new BufferedOutputStream(fos);

            // Creating BufferedOutputStream with specified buffer size
            BufferedOutputStream bosWithBufferSize = new BufferedOutputStream(fos, 8192);

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

In the example above, BufferedOutputStream is created using a FileOutputStream. Additionally, a BufferedOutputStream with a specified buffer size of 8192 bytes is also created.

Writing Data to a BufferedOutputStream

The BufferedOutputStream class provides several methods to write data to the output stream:

  • void write(int b): Writes a single byte.
  • void write(byte[] b): Writes bytes from an array.
  • void write(byte[] b, int off, int len): Writes up to len bytes from an array starting at offset off.

Example

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

public class BufferedOutputStreamWriteExample {
    public static void main(String[] args) {
        try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("example.txt"))) {
            String data = "Hello, World!";
            byte[] bytes = data.getBytes();
            bos.write(bytes);
            System.out.println("Data written to file successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In the example above, BufferedOutputStream writes data to a file named example.txt. The data is written as a byte array.

Flushing the Stream

It is important to flush the BufferedOutputStream to ensure that all buffered data is written to the underlying output stream. This can be done using the flush() method.

Example

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

public class BufferedOutputStreamFlushExample {
    public static void main(String[] args) {
        try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("example.txt"))) {
            String data = "Hello, World!";
            byte[] bytes = data.getBytes();
            bos.write(bytes);
            bos.flush();
            System.out.println("Data flushed and written to file successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In the example above, the flush() method is called to ensure that all buffered data is written to the file.

Closing the Stream

It is important to close the BufferedOutputStream after completing the file operations to release the system resources associated with the stream. This can be done using the close() method.

Example

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

public class BufferedOutputStreamCloseExample {
    public static void main(String[] args) {
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream("example.txt"));
            String data = "Hello, World!";
            byte[] bytes = data.getBytes();
            bos.write(bytes);
            System.out.println("Data written to file successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

In the example above, the BufferedOutputStream is closed in the finally block to ensure that it is closed even if an exception occurs.

Alternatively, you can use the try-with-resources statement, which ensures that the stream is closed automatically.

Example

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

public class BufferedOutputStreamTryWithResourcesExample {
    public static void main(String[] args) {
        try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("example.txt"))) {
            String data = "Hello, World!";
            byte[] bytes = data.getBytes();
            bos.write(bytes);
            System.out.println("Data written to file successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In the example above, the try-with-resources statement is used to automatically close the BufferedOutputStream.

Complete Example

Here is a complete example demonstrating the creation, writing, flushing, and closing of a BufferedOutputStream.

BufferedOutputStreamExample.java

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

public class BufferedOutputStreamExample {
    public static void main(String[] args) {
        try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("example.txt"))) {
            String data = "Hello, World!";
            byte[] bytes = data.getBytes();
            bos.write(bytes);
            bos.flush();
            System.out.println("Data written and flushed to file successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, a BufferedOutputStream is created, data is written to a file, the stream is flushed, and the stream is automatically closed using the try-with-resources statement.

Conclusion

The BufferedOutputStream class in Java is used for improving the performance of output operations by buffering the output data. By understanding how to create, write, flush, and close a BufferedOutputStream, you can effectively handle file I/O operations involving large amounts of data in your Java applications. Remember to always close the stream after use to ensure that system resources are properly released.

Comments