/** * Zips byte array. * * @param input Input bytes. * @param initBufSize Initial buffer size. * @return Zipped byte array. * @throws IOException If failed. */ public static byte[] zipBytes(byte[] input, int initBufSize) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(initBufSize); try (ZipOutputStream zos = new ZipOutputStream(bos)) { ZipEntry entry = new ZipEntry(""); try { entry.setSize(input.length); zos.putNextEntry(entry); zos.write(input); } finally { zos.closeEntry(); } } return bos.toByteArray(); }
static void testCopyFileToOuputStream(int size) throws IOException { Path source = createTempFile("blah", null); try { byte[] b = new byte[size]; rand.nextBytes(b); write(source, b); ByteArrayOutputStream out = new ByteArrayOutputStream(); long n = copy(source, out); assertTrue(n == size); assertTrue(out.size() == size); byte[] read = out.toByteArray(); assertTrue(Arrays.equals(read, b)); // check output stream is open out.write(0); assertTrue(out.size() == size + 1); } finally { delete(source); } }