PUBLISHED ON: MAY 3, 2021
Java ByteArrayInputStream close() Method
In this tutorial, we will learn about the close()
method of the ByteArrayInputStream class in Java. This method is used to close the input stream and release all the system resources attached to it, to the Garbage collector. We won't be getting any error if we invoke any of the methods of this class even after the calling close()
method.
Syntax:
This is the syntax declaration of this method. It does not accept any parameter and doesn't return any value.
public void close()
Example: ByteArrayInputStream close() method
In this example, we are reading the data from the stream, once we finish the reading data from the stream we call the close() method to release all the resources related to the stream.
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class StudyTonight
{
public static void main(String[] args) throws IOException
{
byte[] buf = {1, 2, 3, 4, 5};
ByteArrayInputStream byteArrayInputStr = new ByteArrayInputStream(buf);
int b = 0;
while ((b = byteArrayInputStr.read()) != -1)
{
System.out.print(" " + b);
}
byteArrayInputStr.close();
}
}
1 2 3 4 5
Example: ByteArrayInputStream close() method
Releasing resources linked with the stream is necessary to reduce unnecessary use of resources, in this example, we call the close() method to release the resources linked with the stream.
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);
byteArrayInputStream.close();
}
}
Remaining bytes in buffer: 5
Conclusion:
In this tutorial, we learned about the close()
method of the ByteArrayInputStream class in Java, which closes this input stream and releases any system resources linked with this stream.