IOUtils { public static void readFully(Reader reader, char[] buffer, int offset) throws IOException { int originalOffset = offset; int expected = buffer.length - offset; while (offset < buffer.length) { int numRead = reader.read(buffer, offset, buffer.length - offset); if (numRead < 0) { throw new IOException( String.format("Reached end of stream earlier than expected. Expected to read %d bytes. Actual: %d", expected, offset - originalOffset)); } offset += numRead; } }  static void readFully(Reader reader, char[] buffer, int offset);  }
@Test public void testReadFully() throws Exception { String myMessage = "{this is my message}"; byte[] bytes = myMessage.getBytes(Charsets.UTF_8); InputStream stream = new ByteArrayInputStream(bytes); Reader reader = new InputStreamReader(stream); char[] buffer = new char[myMessage.length()]; IOUtils.readFully(reader, buffer, 0); for (int i = 0; i < myMessage.length(); i++) { assertEquals(buffer[i], myMessage.charAt(i)); } }
@Test public void testReadFullyPartial() throws Exception { String myMessage = "{this is my message}"; byte[] bytes = myMessage.getBytes(Charsets.UTF_8); InputStream stream = new ByteArrayInputStream(bytes); Reader reader = new InputStreamReader(stream); char[] partialBuffer = new char[myMessage.length()/2]; IOUtils.readFully(reader, partialBuffer, 0); for (int i = 0; i < partialBuffer.length; i++) { assertEquals(partialBuffer[i], myMessage.charAt(i)); } }
@Test public void testEmptyReadFully() throws Exception { Reader reader = mock(Reader.class); when(reader.read(any(char[].class), anyInt(), anyInt())) .thenReturn(-1); char[] buffer = new char[10]; try { IOUtils.readFully(reader, buffer, 0); fail(); } catch (IOException e) { } }
@Test public void testReadFullyRemainder() throws Exception { String myMessage = "{this is my message}"; byte[] bytes = myMessage.getBytes(Charsets.UTF_8); InputStream stream = new ByteArrayInputStream(bytes); Reader reader = new InputStreamReader(stream); char[] buffer = new char[myMessage.length()]; IOUtils.readFully(reader, buffer, myMessage.length()/2); for (int i = 0; i < myMessage.length(); i++) { if (i < myMessage.length()/2) { assertEquals(buffer[i], 0); } else { assertEquals(buffer[i], myMessage.charAt(i - myMessage.length()/2)); } } }
@Test public void testIncompleteReadFully() { String myMessage = "{this is my message}"; byte[] bytes = myMessage.getBytes(Charsets.UTF_8); InputStream stream = new ByteArrayInputStream(bytes); Reader reader = new InputStreamReader(stream); char[] buffer = new char[myMessage.length() * 2]; try { IOUtils.readFully(reader, buffer, 0); fail(); } catch (IOException e) { } stream = new ByteArrayInputStream(bytes); reader = new InputStreamReader(stream); try { IOUtils.readFully(reader, buffer, myMessage.length()/2); fail(); } catch (IOException e) { } }