StreamUtils { public static int read(InputStream input, byte[] buffer) throws IOException { if(input == null || buffer == null) { return -1; } int remaining = buffer.length; while (remaining > 0) { int location = buffer.length - remaining; int count = input.read(buffer, 0 + location, remaining); if (EOF == count) { break; } remaining -= count; } return buffer.length - remaining; } private  StreamUtils(); static int read(InputStream input, byte[] buffer); static byte[] toByteArray(InputStream input);  }
@Test public void shouldReadThreeBytes() throws IOException { byte[] bytes = ByteUtils.hexStringToByteArray("af66b1"); ByteArrayInputStream stream = new ByteArrayInputStream(bytes); byte[] buffer = new byte[3]; int read = StreamUtils.read(stream, buffer); Assert.assertEquals(3, read); Assert.assertEquals(3, buffer.length); Assert.assertEquals("af66b1", ByteUtils.toHexString(buffer)); }
@Test public void shouldNotCrashOnNullBufferInput() throws IOException { byte[] bytes = ByteUtils.hexStringToByteArray("af66b1"); ByteArrayInputStream stream = new ByteArrayInputStream(bytes); int read = StreamUtils.read(stream, null); Assert.assertEquals(-1, read); }
@Test public void shouldNotCrashOnNullStreamInput() throws IOException { int read = StreamUtils.read(null, new byte[3]); Assert.assertEquals(-1, read); }