Home » Java programming language

Java PushbackInputStream available() Method with Example

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

PushbackInputStream Class available() method

  • available() method is available in java.io package.
  • available() method is used to return an approximate of the number of available bytes left that can be read from this PushbackInputStream without blocking by the next call of a method for this PushbackInputStream.
  • 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 returning available bytes.
    IOException: This exception may throw when getting any input/output error while performing or close the stream by its close() method.

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 number of available bytes left that can be read from this PushbackInputStream without blocking.

Example:

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

import java.io.*;

public class AvailableOfPBIS {
    public static void main(String[] args) throws Exception {
        byte[] b_arr = {
            97,
            98,
            99,
            100
        };
        int count = 0;
        InputStream is_stm = null;
        PushbackInputStream pb_stm = null;

        try {
            // Instantiates ByteArrayOutputStream and PushbackInputStream
            is_stm = new ByteArrayInputStream(b_arr);
            pb_stm = new PushbackInputStream(is_stm);

            // By using available() method is to
            // return available bytes
            int avail_byte = pb_stm.available();
            System.out.println("pb_stm.available(): " + avail_byte);

            // Loop to read till reach its end
            for (int i = 0; i < b_arr.length; ++i) {
                // By using read() method is to 
                // convert byte into char
                char ch = (char) pb_stm.read();
                System.out.println("ch: " + ch);
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
        } finally {
            if (is_stm != null)
                is_stm.close();
            if (pb_stm != null)
                pb_stm.close();
        }
    }
}

Output

pb_stm.available(): 4
ch: a
ch: b
ch: c
ch: d



Comments and Discussions!

Load comments ↻






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