JavaRush /Java Blog /Random EN /adding an empty directory to a zip archive
DefNeo
Level 36

adding an empty directory to a zip archive

Published in the Random EN group
In general, there is such a question in the interview for Level31 number 5: How to add a directory to the archive? For myself, I understood this question as adding an empty directory to a ready-made zip archive. Here is the code. In it, text files are added to a given archive, but an empty folder is not, maybe someone knows why? Main: public class Main { public static void main(String[] args) { String[] myFiles = {"D:\\forJava\\MyArtifactName\\packForTest\\res2.txt", "D:\\forJava\\MyArtifactName\\packForTest\\res.txt", "D:\\forJava\\MyArtifactName\\packForTest\\res4.txt", "D:\\forJava\\MyArtifactName\\packForTest\\testDir" }; String zipFile = "D:\\forJava\\MyArtifactName\\packForTest\\res.zip"; ZipUtility zipUtil = new ZipUtility(); try { zipUtil.zip(myFiles, zipFile); } catch (Exception ex) { // some errors occurred ex.printStackTrace(); } } } ZipUtility.java: import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipUtility { private static final int BUFFER_SIZE = 4096; public void zip(List listFiles, String destZipFile) throws IOException { ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destZipFile)); for (File file : listFiles) { if (file.isDirectory()) { zipDirectory(file, file.getName(), zos); } else { zipFile(file, zos); } } zos.flush(); zos.close(); } public void zip(String[] files, String destZipFile) throws IOException { List listFiles = new ArrayList (); for (int i = 0; i < files.length; i++) { listFiles.add(new File(files[i])); } zip(listFiles, destZipFile); } private void zipDirectory(File folder, String parentFolder, ZipOutputStream zos) throws IOException { for (File file : folder.listFiles()) { if (file.isDirectory()) { zipDirectory(file, parentFolder + "/" + file.getName(), zos); continue; } zos.putNextEntry(new ZipEntry(parentFolder + "/" + file.getName())); BufferedInputStream bis = new BufferedInputStream( new FileInputStream(file)); long bytesRead = 0; byte[] bytesIn = new byte[BUFFER_SIZE]; int read = 0; while ((read = bis.read(bytesIn)) != -1) { zos.write(bytesIn, 0, read); bytesRead += read; } zos.closeEntry(); } } private void zipFile(File file, ZipOutputStream zos) throws IOException { zos.putNextEntry(new ZipEntry(file.getName())); BufferedInputStream bis = new BufferedInputStream(new FileInputStream( file)); long bytesRead = 0; byte[] bytesIn = new byte[BUFFER_SIZE]; int read = 0; while ((read = bis.read(bytesIn)) != -1) { zos.write(bytesIn, 0, read); bytesRead += read; } zos.closeEntry(); } }
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION