IOUtils { public static String inputStreamAsString(final InputStream inputStream, String charEncoding) throws IOException { if (charEncoding == null){ charEncoding = SYSTEM_CHAR_SET; } StringWriter sw = new StringWriter(); InputStreamReader in = new InputStreamReader(inputStream, charEncoding); char[] buffer = new char[4096]; int bytesRead; while (-1 != (bytesRead = in.read(buffer))) { sw.write(buffer, 0, bytesRead); } return sw.toString(); }  static String inputStreamAsString(final InputStream inputStream, String charEncoding); static void closeQuietly(final InputStream inputStream); static final String SYSTEM_CHAR_SET; }
@Test public void testInputStreamAsString() throws Exception { ByteArrayInputStream bais = new ByteArrayInputStream("This is a string".getBytes()); assertEquals("This is a string", IOUtils.inputStreamAsString(bais, null)); byte[] utf8 = {0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x61, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, (byte)0xc2, (byte)0xa9}; bais = new ByteArrayInputStream(utf8); assertEquals("This is a string©", IOUtils.inputStreamAsString(bais, "UTF-8")); InputStream failingIs = Mockito.mock(InputStream.class); when(failingIs.read(any(byte[].class), anyInt(), anyInt())).thenThrow(new IOException("An IO Exception")); Exception expected = null; try{ IOUtils.inputStreamAsString(failingIs, "UTF-8"); }catch (Exception e){ expected = e; } assertNotNull(expected); }