Подтвердить что ты не робот

Каталогов в zip файле при использовании java.util.zip.ZipOutputStream

Допустим, у меня есть файл t.txt, каталог t и другой файл t/t2.txt. Если я использую утилиту linux zip "zip -r t.zip t.txt t", я получаю zip файл со следующими записями в них (unzip -l t.zip):

Archive:  t.zip
  Length     Date   Time    Name
 --------        ----      ----      ----
        9  04-11-09 09:11   t.txt
        0  04-11-09 09:12   t/
      15  04-11-09 09:12   t/t2.txt
 --------                           -------
       24                          3 files

Если я попытаюсь воспроизвести это поведение с помощью java.util.zip.ZipOutputStream и создать запись zip для каталога, java выдает исключение. Он может обрабатывать только файлы. Я могу создать запись t/t2.txt в zip файле и добавить к нему содержимое файла t2.txt, но я не могу создать каталог. Почему это?

4b9b3361

Ответ 1

ZipOutputStream может обрабатывать пустые каталоги, добавив переднюю-косую черту / после имени папки. Попробуйте (из)

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());
        }
    }
}

Ответ 2

Просто перейдите через источник java.util.zip.ZipEntry. Он обрабатывает каталог ZipEntry, если его имя заканчивается символами "/". Просто суффикс имени каталога с помощью "/".

Отметьте этот пример, чтобы закрепить только пустые каталоги, http://bethecoder.com/applications/tutorials/showTutorials.action?tutorialId=Java_ZipUtilities_ZipEmptyDirectory

Удачи.

Ответ 3

Программа Java для Zip (папки содержат либо пустые, либо полные)

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);
                }
            }
        }
    }
}

Ответ 4

Как и другие, упомянутые здесь, чтобы добавить пустой каталог, добавьте "/" в имя каталога. Обратите внимание: НЕ добавлять File.separator(равно "\" ), которые фактически добавляют пустой файл в zip.

Мне потребовалось некоторое время, чтобы понять, в чем была моя ошибка - надеюсь, что я сохраню еще какое-то время...

Ответ 5

Вы можете добавить "/" в конце имени папки. Просто используйте следующую команду:

zip.putNextEntry(new ZipEntry("xml/"));