Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Java ByteArrayInputStream available() Method

In this tutorial, we will learn about the available() method of the ByteArrayInputStream class in Java. This method provides the remaining number of bytes that can be read from this input stream. It is a non-static method, available in the java.io package, which should only be accessed using class objects. It may throw an exception while checking the bytes.

Syntax:

This is the syntax declaration of this method. It does not accept any parameter and it returns the total number of bytes remaining to be read from this input stream.

public int available()

Example: ByteArrayInputStream available() Method

In this example by using the available() method, we are going to check how many bytes are available in the buffer, it will return the int value of a number of bytes. Here it is returning the value four and we can clearly see the four elements are there in the given buffer.

import java.io.ByteArrayInputStream;
import java.io.IOException;
public class StudyTonight 
{
	public static void main(String[] args) throws IOException 
	{ 
		byte[] buffer = { 4, 7, 8, 3, 1 }; 

		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buffer); 

		int number = byteArrayInputStream.available(); 

		System.out.println("Remaining bytes in buffer: "+ number); 
	}  
}


Remaining bytes in buffer: 5

Example: ByteArrayInputStream available() Method

In the buffer given below, there is only one byte is available so this method is returning a 1 value to indicate that 1 byte is available in the given buffer.

import java.io.ByteArrayInputStream;
import java.io.IOException;
public class StudyTonight 
{
	public static void main(String[] args) throws IOException 
	{ 
		byte[] buffer = {1}; 

		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buffer); 

		int number = byteArrayInputStream.available(); 

		System.out.println("Remaining bytes in buffer: "+ number); 
	}  
}


Remaining bytes in buffer: 1

mail Conclusion:

In this tutorial, we learned about the available() method of the ByteArrayInputStream class in Java, which is used to return the actual number of remaining bytes to be read by the reader in the current input stream.