StreamUtil { public static void copyStream(InputStream input, OutputStream output, int expected) throws IOException { if (input == null || output == null) { return; } if (expected <= 0) { copyStream(input, output); } else { byte[] bytes = new byte[Math.min(expected, BUFSIZE)]; int totalRead = 0; int bytesRead = 0; while (totalRead < expected) { bytesRead = input.read(bytes, 0, bytes.length); output.write(bytes, 0, bytesRead); totalRead = totalRead + bytesRead; } output.flush(); } }  static File createFile(InputStream input, int expected); static File createFile(InputStream input, int expected, String dir); static void copyStream(InputStream input, OutputStream output,
                                int expected); static void copyStream(InputStream input, OutputStream output); static InputStream makeCopy(InputStream input); static void copyAndClose(InputStream input, Writer out); static void copyAndClose(InputStream input, Writer out, Charset charset); static void copyAndClose(InputStream input, OutputStream out);  }
@Test public void testCopyStreamNullInputs() throws Exception { StreamUtil.copyStream(null, null); ByteArrayOutputStream out = new ByteArrayOutputStream(); StreamUtil.copyStream(null, out); assertEquals(0, out.toByteArray().length); StreamUtil.copyStream(new ByteArrayInputStream(TEXT.getBytes()), null); StreamUtil.copyStream(null, null, -1); StreamUtil.copyStream(null, null, 10); StreamUtil.copyStream(null, new ByteArrayOutputStream(), 10); StreamUtil.copyStream(new ByteArrayInputStream(TEXT.getBytes()), null, 10); StreamUtil.copyStream(new ByteArrayInputStream(TEXT.getBytes()), new ByteArrayOutputStream(), -1); }
@Test public void testCopyStreamWithLength() throws Exception { int bytes = TEXT.length(); ByteArrayInputStream in = new ByteArrayInputStream(TEXT.getBytes()); ByteArrayOutputStream out = new ByteArrayOutputStream(); StreamUtil.copyStream(in, out, bytes); assertEquals(TEXT, out.toString()); }
@Test public void testCopyStreamNoLength() throws Exception { ByteArrayInputStream in = new ByteArrayInputStream(TEXT.getBytes()); ByteArrayOutputStream out = new ByteArrayOutputStream(); StreamUtil.copyStream(in, out); assertEquals(TEXT, out.toString()); }