Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
BufferedInputStream
2.1.
Constructors
2.2.
Methods
2.3.
Example
3.
BufferedOutputStream
3.1.
Constructors
3.2.
Methods
3.3.
Example
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024

BufferedInputStream and BufferedOutputStream

Author Yashesvinee V
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

A Stream is a logical connection to exchange a sequence of bytes between a program and a file. Java uses this concept to make input and output operations faster. InputStream can read data from a source, while OutputStream can write data into a destination file. Sometimes, buffers can store the data to be transferred, thereby making the process more efficient. This buffer mechanism in I/O streams can be implemented using the BufferedInput/OutputStream classes in Java. Let’s learn more about these classes in detail.

Must Read, Multithreading in java, Duck Number in Java

BufferedInputStream

The BufferedInputStream class reads data from a stream and uses an internal buffer to store the bytes of data to be read or skipped. This internal buffer array is created along with the BufferedInputStream. The size of the internal buffer is approximately 8192 bytes.

During a read operation, chunks of bytes are stored from the disc to the internal buffer array, from where they are read individually. This significantly saves the amount of time used to contact to disc.

The BufferedInputStream class is a part of the java.io package and extends the InputStream abstract class.

Declaration:

public class BufferedInputStream extends FilterInputStream  

Constructors

  • BufferedInputStream (InputStream in)

    • It creates a BufferedInputStream and saves the given InputStream argument for later use.
       
BufferedInputStream b_in = new BufferedInputStream(InputStream in);

 

  • BufferedInputStream (InputStream in, int size)

    • It creates a BufferedInputStream with specific buffer size and saves the InputStream argument for later use.
       
BufferedInputStream b_in = new BufferedInputStream(InputStream in, int size);

Methods

Method

Description

int available() It returns the estimated number of bytes that can be read or skipped over from this input stream without blocking calls from another method that requests this InputStream.
void close() It closes the InputStream and releases all the resources associated with it.
void mark (int readLimit) It marks a point in the Input stream.
Boolean markSupported() It checks if the input stream supports the mark and reset functions.
int read() It reads the next byte of data from the Input stream.
int read (byte b[ ], int off, int len) It reads a given number of bytes from the Input stream and stores it in the given byte array.
void reset() It resets the position of the stream to the initial one mentioned by the most recent mark function.
long skip(long n) It skips over and discards n bytes of data from the Input stream.

 

Example

Assume ‘hello world!!!’ to be the contents of a file named read.txt present in the current working directory.

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

class Main {
    public static void main(String[] args) {
        try {

            // Creates a FileInputStream
            FileInputStream file = new FileInputStream("read.txt");

            // Creates a BufferedInputStream
            BufferedInputStream b_in = new BufferedInputStream(file);

            System.out.println(b_in.markSupported());
            System.out.println(b_in.available());
            
            // Read first byte
            int i = b_in.read();
            
            while (i != -1) {
                System.out.print((char) i);

                // Reads next byte from the file
                i = b_in.read();
            }
            b_in.close();
        }

        catch (Exception e) {
            System.out.println("Error");
        }
    }
}

 

Output:

true
13
hello world!!!


Practice by yourself on java online compiler.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

BufferedOutputStream

This class implements a buffered output stream that can be used to write bytes to the underlying output stream without making unnecessary calls to the underlying system for each byte. Like BufferedInputStream, it also maintains an internal buffer of 8192 bytes.

During a write operation, the bytes are written into an internal buffer instead of the disc. Once the stream is closed or the buffer is filled, the entire buffer’s content is written onto the disc at once. This significantly saves the amount of time used to communicate with the disc.

The BufferedOutputStream class is part of the java.io package and extends the OutputStream abstract class.

Declaration:

public class BufferedOutputStream extends FilterOutputStream  

Constructors

  • BufferedOutputStream (OutputStream out)

    • It creates a BufferedOutputStream to write data into the specified output stream.
       
BufferedOutputStream b_out = new BufferedOutputStream(OutputStream out);

 

  • BufferedOutputStream (OutputStream out, int size)

    • It creates a BufferedOutputStream to write data into the specified output stream of the given buffer size.
       
BufferedOutputStream b_out = new BufferedOutputStream(OutputStream out, int size);

Methods

Method

Description

void flush() It flushes the buffered output stream.
void write(byte b[ ], int off, int len) It writes a given number of bytes from the byte array into the output stream.
void write (int b) It writes a specific byte into the buffered input stream.

 

Example

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

public class Main {
    public static void main(String[] args) {

        String data = "hello world!!!";

        try {
            // Creates a FileOutputStream
            FileOutputStream file = new FileOutputStream("output.txt");

            // Creates a BufferedOutputStream
            BufferedOutputStream b_out = new BufferedOutputStream(file);

            byte[] arr = data.getBytes();

            // Writes data to the output stream
            b_out.flush();
            b_out.write(arr);
            b_out.close();
        }

        catch (Exception e) {
            System.out.println(e);
        }
    }
}

 

The above code writes ‘hello world!!!’ in the output.txt file, which is stored in the current working directory. 

Also read, Hashcode Method in Java and Swap Function in Java

FAQs

 1. What is the main advantage of using BufferedInput/Output stream?

The use of an internal buffer in BufferedInput/OutputStream avoids unnecessary system calls to transfer a single byte of data one at a time. This reduces processing time and greatly improves performance.
 

 2. What is BufferedReader, and how is it different from BufferedInputStream?

BufferedReader is a class in Java that reads text from an Input stream by buffering characters. The main difference between BufferedReader and BufferedInputStream is that BufferedReader reads characters while BufferedInputStream reads raw bytes.

Key Takeaways

This article extensively discusses the BufferedInput/OutputStream classes in Java. We hope that this blog has helped you enhance your knowledge regarding the constructors and methods of BufferedInput/OutputStream classes and if you would like to learn more, check out our articles on the Coding Ninjas Library. Do upvote our blog to help other ninjas grow. 

Related Links:


Happy Coding!

Live masterclass