I can't understand why there is an error in the code, the topic is InputStream and OutputStream

Have a nice day! Please tell me what is the error in this code.

An error occurs: the output stream was empty when it was not expected.

The task is as follows: Write a void print(InputStream InputStream, OutputStream OutputStream) method that accepts InputStream and OutputStream, reads all bytes from the InputStream, and writes only even bytes to the OutputStream.

Sample input: 3, 10, 4, 5, 7

Example output: 10, 4

My code:

public class Test {
    public static void main(String[] args) throws IOException {
        InputStream stream = new ByteArrayInputStream(new byte[]{2, -11, 7, 51, 64});
        OutputStream outputStream = new ByteArrayOutputStream();
        print(stream, outputStream);

    }


    public static void print(InputStream inputStream, OutputStream outputStream) throws IOException {
        byte result;
        int i;
        while ((i = inputStream.read()) != -1) {
            if ((result = (byte) i) % 2 == 0) {
               outputStream.write(result);
            }
        }
    }
}
Author: user4166, 2020-04-04

1 answers

I summarize the comments: The problem is that you are not working properly with IO.

The problem in the task is that there is a buffer inside ByteArrayOutputStream, which must be "cleaned" after writing using the flush() method, so as not to lose the information that has not yet been written.

The second problem is that you do not close the write and read streams, which in the case of reading/writing from an array does not lead to any disastrous consequences, but in general it is better to use the try-with-resources construction, so you freeing yourself from the need to free up resources and do flush(), everything will be done automatically after exiting the block try.

 1
Author: instahipsta282, 2020-04-04 12:12:52