StreamUtils { public static byte[] getBytesWithoutClosing(InputStream stream) throws IOException { if (stream instanceof ExposedByteArrayInputStream) { return ((ExposedByteArrayInputStream) stream).readAll(); } else if (stream instanceof ByteArrayInputStream) { byte[] ret = new byte[stream.available()]; stream.read(ret); return ret; } SoftReference<byte[]> refBuffer = threadLocalBuffer.get(); byte[] buffer = refBuffer == null ? null : refBuffer.get(); if (buffer == null) { buffer = new byte[BUF_SIZE]; threadLocalBuffer.set(new SoftReference<>(buffer)); } ByteArrayOutputStream outStream = new ByteArrayOutputStream(); while (true) { int r = stream.read(buffer); if (r == -1) { break; } outStream.write(buffer, 0, r); } return outStream.toByteArray(); } private  StreamUtils(); static byte[] getBytesWithoutClosing(InputStream stream);  }
@Test public void testGetBytesFromExposedByteArrayInputStream() throws IOException { InputStream stream = new ExposedByteArrayInputStream(testData); byte[] bytes = StreamUtils.getBytesWithoutClosing(stream); assertArrayEquals(testData, bytes); assertSame(testData, bytes); assertEquals(0, stream.available()); }
@Test public void testGetBytesFromByteArrayInputStream() throws IOException { InputStream stream = new ByteArrayInputStream(testData); byte[] bytes = StreamUtils.getBytesWithoutClosing(stream); assertArrayEquals(testData, bytes); assertEquals(0, stream.available()); }
@Test public void testGetBytesFromInputStream() throws IOException { InputStream stream = new BufferedInputStream(new ByteArrayInputStream(testData)); byte[] bytes = StreamUtils.getBytesWithoutClosing(stream); assertArrayEquals(testData, bytes); assertEquals(0, stream.available()); }