There is a method for reading an array of bytes from the stream, but for some reason it only reads the last cell in the array.
What am I doing wrong?

public void read() { byte[] bytes = { 1, 2, 3, 4 }; try (InputStream in = new ByteArrayInputStream(bytes)) { int b; while ((b = in.read(bytes)) != -1) { System.out.println(b); } } catch (IOException e) { e.printStackTrace(); } } 

Prints in the console only the number 4 . Why?

    1 answer 1

    The read method returns the number of bytes read, so 4 returned.
    In addition, the values ​​are put in the same array from which they are read. This is to ensure that to check that something is read, you need to take another array. For example:

     byte[] bytes = { 1, 2, 3, 4 }; byte[] out = new byte[4]; try (InputStream in = new ByteArrayInputStream(bytes)) { int b; while ((b = in.read(out)) != -1) { System.out.println(b); } } catch (IOException e) { e.printStackTrace(); } System.out.println(Arrays.toString(out)); 

    Now there are four read bytes in the out array.