Reading a File in Java using BufferedInputStream

In this post, we will learn how to read a file in the java BufferedInputStream class.

1. What is BufferedInputStream? 

BufferedInputStream belongs to the java.io package and is a subclass of FilterInputStream. By adding buffering capabilities to input streams, it increases performance by reducing the number of calls to the underlying data source. 

2. How to Read a File Using BufferedInputStream 

Let's walk through a simple example where we read a file byte by byte:

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class BufferedInputStreamDemo {
    public static void main(String[] args) {
        String filePath = "sample.txt";

        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath))) {
            int data;
            while ((data = bis.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            System.out.println("Error reading the file: " + e.getMessage());
        }
    }
}

In this code: 
We've wrapped a FileInputStream instance inside a BufferedInputStream

The read() method reads a byte at a time. When there's no more data to read, it returns -1. 

For illustrative purposes, we cast the byte data to a character for display. If you're working with binary data, you'll handle it differently. 

3. Advantages of Using BufferedInputStream 

Performance: By reading data in larger chunks rather than one byte at a time, BufferedInputStream reduces the IO operations' overhead, resulting in faster data processing. 

Flexibility: Since it reads raw bytes, BufferedInputStream can handle any file type, be it text or binary, like images or audio files. 

4. Things to Consider 

Binary Data: If you're reading binary files (like images), avoid converting bytes to characters. Instead, process the bytes directly or write them to another OutputStream. 

Buffer Size: By default, BufferedInputStream uses an internal buffer of 8 KB. If needed, you can specify a different buffer size in the constructor. 

5. Closing Streams 

Always ensure to close your streams to free up system resources. The try-with-resources statement, introduced in Java 7, makes this easier by automatically closing the stream at the end of the statement.

6. Conclusion 

Whether you're working with text files or managing binary data, BufferedInputStream offers a fast and efficient way to read data in Java. By understanding its capabilities and how to use it effectively, you can streamline your file-processing tasks and handle a wider variety of file types.

Comments