


import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.SequenceInputStream;

public class ReadWithNullAtEOF {

    public static void main(String[] args) throws IOException {
        new ReadWithNullAtEOF().testNull_EOF();
    }

    /**
     * Verifying the case - NullPointerException if the end of the last contained stream has not been reached and b is null.
     * case - b is null but the end of the last contained stream has been reached, shall not throw NPE
     */

    public void testNull_EOF() throws IOException {
        byte[] bytes1 = {1, 2};
        byte[] bytes2 = {3, 4, 5};
        ByteArrayInputStream byteArrayInputStream1 = new ByteArrayInputStream(bytes1);
        ByteArrayInputStream byteArrayInputStream2 = new ByteArrayInputStream(bytes2);
        try (SequenceInputStream sequenceInputStream = new SequenceInputStream(
                byteArrayInputStream1, byteArrayInputStream2)) {
            byte[] actualBytesRead1 = new byte[4];
            byte[] actualBytesRead2 = new byte[10];

            //The read method of SequenceInputStream tries to read the data from byteArrayInputStream1
            int bytesRead1 = sequenceInputStream.read(actualBytesRead1, 0, 4);
            //The read method of SequenceInputStream tries to read the data from byteArrayInputStream2
            int bytesRead2 = sequenceInputStream.read(actualBytesRead2, 0, 10);
            System.out.println(" The bytes read are " + bytesRead1 + " " + bytesRead2);
            /*
             Now that the SequenceInputStream has reached end of the last contained stream, invoking read with null
             shall return -1 instead of NPE.
             */
           /* bytesRead2 = sequenceInputStream.read(new byte[1], 0, 1);
            if (bytesRead2 == -1) {
                System.out.println("OKAY - As Expected");
            }*/

            bytesRead2 = sequenceInputStream.read(null, 0, 1);
            if (bytesRead2 == -1) {
                System.out.println("OKAY - As Expected no NPE");
            }
        }
    }
}
