directories in a zip file when using java.util.zip.ZipOutputStream

后端 未结 6 1606
北荒
北荒 2020-12-04 13:40

Lets say I have a file t.txt, a directory t and another file t/t2.txt. If I use the linux zip utility \"zip -r t.zip t.txt t\", I get a zip file with the following entries i

相关标签:
6条回答
  • 2020-12-04 13:50

    Java Program to Zip(folders contains either empty or full ones)

    public class ZipUsingJavaUtil {
        /*
         * Zip function zip all files and folders
         */
        @Override
        @SuppressWarnings("finally")
        public boolean zipFiles(String srcFolder, String destZipFile) {
            boolean result = false;
            try {
                System.out.println("Program Start zipping the given files");
                /*
                 * send to the zip procedure
                 */
                zipFolder(srcFolder, destZipFile);
                result = true;
                System.out.println("Given files are successfully zipped");
            } catch (Exception e) {
                System.out.println("Some Errors happned during the zip process");
            } finally {
                return result;
            }
        }
    
        /*
         * zip the folders
         */
        private void zipFolder(String srcFolder, String destZipFile) throws Exception {
            ZipOutputStream zip = null;
            FileOutputStream fileWriter = null;
            /*
             * create the output stream to zip file result
             */
            fileWriter = new FileOutputStream(destZipFile);
            zip = new ZipOutputStream(fileWriter);
            /*
             * add the folder to the zip
             */
            addFolderToZip("", srcFolder, zip);
            /*
             * close the zip objects
             */
            zip.flush();
            zip.close();
        }
    
        /*
         * recursively add files to the zip files
         */
        private void addFileToZip(String path, String srcFile, ZipOutputStream zip, boolean flag) throws Exception {
            /*
             * create the file object for inputs
             */
            File folder = new File(srcFile);
    
            /*
             * if the folder is empty add empty folder to the Zip file
             */
            if (flag == true) {
                zip.putNextEntry(new ZipEntry(path + "/" + folder.getName() + "/"));
            } else { /*
                     * if the current name is directory, recursively traverse it
                     * to get the files
                     */
                if (folder.isDirectory()) {
                    /*
                     * if folder is not empty
                     */
                    addFolderToZip(path, srcFile, zip);
                } else {
                    /*
                     * write the file to the output
                     */
                    byte[] buf = new byte[1024];
                    int len;
                    FileInputStream in = new FileInputStream(srcFile);
                    zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
                    while ((len = in.read(buf)) > 0) {
                        /*
                         * Write the Result
                         */
                        zip.write(buf, 0, len);
                    }
                }
            }
        }
    
        /*
         * add folder to the zip file
         */
        private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip) throws Exception {
            File folder = new File(srcFolder);
    
            /*
             * check the empty folder
             */
            if (folder.list().length == 0) {
                System.out.println(folder.getName());
                addFileToZip(path, srcFolder, zip, true);
            } else {
                /*
                 * list the files in the folder
                 */
                for (String fileName : folder.list()) {
                    if (path.equals("")) {
                        addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip, false);
                    } else {
                        addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip, false);
                    }
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-04 13:52

    ZipOutputStream can handle empty directories by adding a forward-slash / after the folder name. Try (from)

    public class Test {
        public static void main(String[] args) {
            try {
                FileOutputStream f = new FileOutputStream("test.zip");
                ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(f));
                zip.putNextEntry(new ZipEntry("xml/"));
                zip.putNextEntry(new ZipEntry("xml/xml"));
                zip.close();
            } catch(Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-04 13:52

    You can add "/" at the end of folder name. Just use the following command:

    zip.putNextEntry(new ZipEntry("xml/"));
    
    0 讨论(0)
  • 2020-12-04 13:57

    String dir = "E:\Infor\Marketing\JobLog\Cloud_MomBuild_NoMirror";

    public void downloadAsZip() throws IOException {
        ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(byteOutputStream);
        Path folderPath = Paths.get(dir);
        String folderName = "Output";
        for (File file : folderPath.toFile().listFiles()) {
            String path = folderName + "/" + file.getName();
            if (file.isDirectory()) {
                writeFolderToZip(zipOutputStream, file, path);
            } else {
                writeFileToZip(zipOutputStream, file, path);
            }
        }
    }
    
    public void writeFileToZip(ZipOutputStream zipOutputStream, File file, String path) throws IOException {
        zipOutputStream.putNextEntry(new ZipEntry(path));
        FileInputStream fileInputStream = new FileInputStream(file);
        IOUtils.copy(fileInputStream, zipOutputStream);
        fileInputStream.close();
        zipOutputStream.closeEntry();
    }
    
    public void writeFolderToZip(ZipOutputStream zipOutputStream, File dir, String path) throws IOException {
        for (File file : dir.listFiles()) {
            String dirPath = path + "/" + file.getName();
            if (file.isDirectory()) {
                writeFolderToZip(zipOutputStream, file, dirPath);
            } else {
                writeFileToZip(zipOutputStream, file, dirPath);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-04 14:05

    Just go through the source of java.util.zip.ZipEntry. It treats a ZipEntry as directory if its name ends with "/" characters. Just suffix the directory name with "/".

    Check this example for zipping just the empty directories, http://bethecoder.com/applications/tutorials/showTutorials.action?tutorialId=Java_ZipUtilities_ZipEmptyDirectory

    Good luck.

    0 讨论(0)
  • 2020-12-04 14:13

    Like others said here to add empty directory add "/" to the directory name. Pay attention NOT to add File.separator (equals to "\") which actually add an empty file to the zip.

    It took me a while to understand what was my mistake - hope I save other some time...

    0 讨论(0)
提交回复
热议问题