What is the usage of ByteArrayInputStream in Java?
The ByteArrayInputStream class in Java is used to read data as an input stream from a byte array. It inherits all methods from the InputStream class and implements them.
Here is a usage example of ByteArrayInputStream:
- To create a ByteArrayInputStream object, you can do so by passing in a byte array. For example:
byte[] byteArray = {1, 2, 3, 4, 5};
ByteArrayInputStream inputStream = new ByteArrayInputStream(byteArray);
- Reading data: It is possible to use the read() method of InputStream to read a byte of data from a ByteArrayInputStream. For example:
int data = inputStream.read();
System.out.println(data);
Note: The read() method returns an integer value representing a byte. If the end of the stream has been reached, it returns -1.
- Resetting the stream position: You can use the reset() method to set the position of the stream back to the initial position. This allows you to reread data that has already been read before. For example:
inputStream.reset();
int data = inputStream.read();
System.out.println(data);
- Close the stream: After using ByteArrayInputStream, you should call the close() method to release resources. For example:
inputStream.close();
It is important to note that ByteArrayInputStream is a stream based on byte arrays, so it is suitable for reading existing byte array data. If you need to read data from other sources such as files or networks, you can use other types of streams, such as FileInputStream or SocketInputStream.