Java ByteArrayInputStream
ByteArrayInputStream
is a class in Java that is used to read data from an array of bytes as an input stream. It is a subclass of InputStream
, which is an abstract class that provides a standard way of reading data from different sources in the form of bytes.
Here's an example of using the ByteArrayInputStream
class to read data from a byte array:
import java.io.*; public class ByteArrayInputStreamExample { public static void main(String[] args) { try { byte[] data = {72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33}; ByteArrayInputStream input = new ByteArrayInputStream(data); int character; while ((character = input.read()) != -1) { System.out.print((char) character); } input.close(); } catch (IOException e) { e.printStackTrace(); } } }
In this example, we create a byte array data
containing some text in ASCII format. We then create a ByteArrayInputStream
object and pass the data
array as a parameter. We read the data from the input stream using the read
method of the ByteArrayInputStream
object and cast each byte to a character using the (char)
operator. Finally, we close the input stream using the close
method.
The ByteArrayInputStream
class provides several other methods for reading data from an array of bytes, including read(byte[] b, int off, int len)
, which reads up to len
bytes of data from the input stream into the byte array b
, starting at the specified offset off
, and skip(long n)
, which skips over and discards n
bytes of data from the input stream.
Overall, the ByteArrayInputStream
class provides a flexible and efficient way of reading data from a byte array in Java. By using the various methods provided by ByteArrayInputStream
, you can read data from byte arrays in a variety of different ways depending on your specific needs.