Java BufferedInputStream available() Method with Example

BufferedInputStream Class available() method: Here, we are going to learn about the available() method of BufferedInputStream Class with its syntax and example.
Submitted by Preeti Jain, on March 01, 2020

BufferedInputStream Class available() method

  • available() method is available in java.io package.
  • available() method is used to return the number of unread bytes available from an input stream without blocking by the next calling of a method for this InputStream.
  • available() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • available() method may throw an exception at the time of checking available bytes.
    IOException: This exception may throw while performing input/output operation.

Syntax:

    public int available();

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of the method is int, it returns the amount of unread unblocking bytes from this input stream.

Example:

// Java program to demonstrate the example 
// of int available() method of BufferedInputStream

import java.io.*;

public class AvailableBAIS {
    public static void main(String[] args) throws Exception {
        byte[] by = {
            97,
            98,
            98,
            99
        };

        // Instantiates ByteArrayInputStream 
        ByteArrayInputStream byte_s = new ByteArrayInputStream(by);

        // To read till EOF
        while (byte_s.available() > 0) {

            // By using available() method is to
            // return the no. of bytes to be left 
            // for reading
            Integer n_byte = byte_s.available();
            System.out.println("Left avail bytes = " + n_byte);

            // Read char value one by one 
            // by using read() from this File
            char ch = (char) byte_s.read();

            // Display value of char
            System.out.println("byte_s.read(): ");
            System.out.println("ch: " + ch);
        }

        // Close the stream 
        byte_s.close();
    }
}

Output

Left avail bytes = 4
byte_s.read(): 
ch: a
Left avail bytes = 3
byte_s.read(): 
ch: b
Left avail bytes = 2
byte_s.read(): 
ch: b
Left avail bytes = 1
byte_s.read(): 
ch: c



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.