39

ファイルt.txt、ディレクトリt、および別のファイルt/t2.txtがあるとします。Linuxのzipユーティリティ「zip-rt.zipt.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は例外をスローします。ファイルのみを処理できます。zipファイルにat/t2.txtエントリを作成し、それにt2.txtファイルの内容を使用して追加することはできますが、ディレクトリを作成できません。何故ですか?

4

6 に答える 6

63

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());
        }
    }
}
于 2009-04-11T16:29:59.120 に答える
24

java.util.zip.ZipEntryのソースを確認するだけです。名前が「/」文字で終わる場合は、ZipEntryをディレクトリとして扱います。ディレクトリ名の末尾に「/」を付けるだけです。

空のディレクトリだけを圧縮するには、この例を確認してください。http://bethecoder.com/applications/tutorials/showTutorials.action?tutorialId= Java_ZipUtilities_ZipEmptyDirectory

幸運を。

于 2011-05-25T07:28:57.920 に答える
17

Java Program to 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);
                }
            }
        }
    }
}
于 2011-06-24T19:33:16.430 に答える
16

他の人がここで言ったように、空のディレクトリを追加するには、ディレクトリ名に「/」を追加します。実際に空のファイルをzipに追加するFile.separator( "\"に等しい)を追加しないように注意してください。

私の間違いが何であるかを理解するのに少し時間がかかりました-私が他の時間を節約することを願っています...

于 2014-11-17T12:09:52.760 に答える
9

フォルダ名の末尾に「/」を追加できます。次のコマンドを使用するだけです。

zip.putNextEntry(new ZipEntry("xml/"));
于 2009-06-12T08:14:33.090 に答える
0

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);
        }
    }
}
于 2019-12-03T07:24:13.933 に答える