ZipUtils { public static void zip(File fileToZip, File destination) throws IOException { if (fileToZip == null) throw new NullPointerException("The file to zip can not be null"); if (!fileToZip.exists()) throw new FileNotFoundException("The file to zip does not exist"); if (destination == null) throw new NullPointerException("The destination can not be null"); final ListFilesFileVisitor visitor = new ListFilesFileVisitor(); Files.walkFileTree(fileToZip.toPath(), visitor); final List<File> filesToZip = visitor.getFiles(); try (final ZipOutputStream zipOutput = new ZipOutputStream(new FileOutputStream(destination))) { ZipEntry entry; String entryName; final byte[] buffer = new byte[1024]; int length; final String prefixToDelete; if (fileToZip.isDirectory()) { prefixToDelete = fileToZip.getAbsolutePath() + File.separator; } else { prefixToDelete = ""; } for (File file : filesToZip) { LOGGER.fine("Compressing file: " + file.getAbsolutePath()); entryName = file.getAbsolutePath().substring(prefixToDelete.length(), file.getAbsolutePath().length()); entryName = entryName.replaceAll("\\\\", "/"); LOGGER.log(FINEST, "Entry name: {0}", entryName); if (file.isDirectory()) { entry = new ZipEntry(entryName + "/"); zipOutput.putNextEntry(entry); } else { entry = new ZipEntry(entryName); zipOutput.putNextEntry(entry); try (final FileInputStream fileInput = new FileInputStream(file)) { while ((length = fileInput.read(buffer)) > 0) { zipOutput.write(buffer, 0, length); } } } } zipOutput.closeEntry(); zipOutput.flush(); } LOGGER.fine("File compressed"); } private  ZipUtils(); static void unzip(File archive, File destination); static void unzip(InputStream archive, File destination); static void zip(File fileToZip, File destination);  }
@Test public void zip() throws IOException { final File zip = new File(testResultsDir, "zipped.zip"); ZipUtils.zip(resourcesDir, zip); try (final FileInputStream fileInput = new FileInputStream(zip); final ZipInputStream input = new ZipInputStream(fileInput)) { final int expectedNumberOfEntries = 5; int numberOfEntries = 0; ZipEntry entry; while ((entry = input.getNextEntry()) != null) { numberOfEntries++; switch (entry.getName()) { case "dir/otherDir/otherDirTest.html": assertFalse(entry.isDirectory(), "otherDirTest.html is a directory"); break; case "dir/dirTest.txt": assertFalse(entry.isDirectory(), "dirTest.txt is a directory"); break; case "archive.zip": assertFalse(entry.isDirectory(), "archive.zip is a directory"); break; case "test.html": assertFalse(entry.isDirectory(), "test.html is a directory"); break; case "test.txt": assertFalse(entry.isDirectory(), "test.txt is a directory"); break; default: fail("Unknown entry name: [" + entry.getName() + "]"); } } assertEquals(expectedNumberOfEntries, numberOfEntries); } zip.delete(); }