Java UnsynchronizedByteArrayInputStream-class And Method Code Example


Here is an example of how to use the UnsynchronizedByteArrayInputStream class from the Apache Commons IO library to create an input stream from a byte array in Java:

import org.apache.commons.io.input.UnsynchronizedByteArrayInputStream;

public class ByteArrayInputStreamExample {
    public static void main(String[] args) {
        byte[] data = "Hello World!".getBytes();
        UnsynchronizedByteArrayInputStream inputStream = new UnsynchronizedByteArrayInputStream(data);

        int value;
        while ((value = inputStream.read()) != -1) {
            // Do something with the data
            System.out.print((char) value);
        }
        inputStream.close();
    }
}

In this example, a byte array is created from a string "Hello World!" and passed to the UnsynchronizedByteArrayInputStream constructor.

A while loop is used to read the data from the input stream and it is displayed on the console. The inputStream.read() method returns -1 when the end of the stream is reached.

Finally, all the streams are closed after reading the data.

The UnsynchronizedByteArrayInputStream is similar to the ByteArrayInputStream, but it is not synchronized, which means that multiple threads can access the stream without the need for explicit synchronization. This can lead to a performance increase, but it also means that the client code must ensure thread safety.