有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何防止生成空zip文件

我正在制作一个压缩的图像文件。但若并没有找到映像,那个么它会生成一个类似java.util.zip.ZipException: ZIP file must have at least one entry的异常。我正在处理异常,但正在生成一个大小为0的空zip。所以请帮我解决这个问题

    try {
        // create the ZIP file

        ZipOutputStream out = getOutputStream(subpart, destinationZipPath);

        /*
         * ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
         * destinationZipPath));
         */
        // compress the files
        LOGGER.error("zip creation is started @" + new Date().toString());
        for (String fileNameDB : filesTobeZipped) {
            // To check duplication of filename in zip creation
            if (!filesHash.containsKey(fileNameDB)) {
                filesHash.put(fileNameDB, fileNameDB);
                File f = new File(sourceFolder + fileNameDB);
                // to chk file is exists on physical location or not
                if (f.exists()) {
                    if (fileCount >= batchFileLimit) {
                        out.close();
                        subpart++;
                        out = getOutputStream(subpart, destinationZipPath);
                        fileCount = 0;
                        // overallSize=0;
                    }
                    FileInputStream in = new FileInputStream(f);
                    // add ZIP entry to output stream
                    out.putNextEntry(new ZipEntry(f.getName()));
                    // transfer bytes from the file to the ZIP file
                    int len;
                    while ((len = in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }
                    // complete the entry
                    out.closeEntry();
                    in.close();
                    fileCount++;
                } else {
                }
            }

        }
        // complete the ZIP file
        out.close(); // Exception if fileCount=0;
        return true;
        // return zipfile;
    } catch (IOException ex) {
        return false;
    }

共 (2) 个答案

  1. # 1 楼答案

    您不能在检测到第一个现有文件后创建ZIP流吗。就像

    ZipOutputStream out = null;
    
    for (String fileNameDB : filesTobeZipped) {
        if (new File(fileNameDB).exists()) {
            if (out == null) {
                out= ZipOutputStream out = getOutputStream(subpart, destinationZipPath);
            }
    
            // do other operations
        }
    }
    
  2. # 2 楼答案

    你可以这样做:

    ZipOutputStream out = null;
    try {
        out = getOutputStream(subpart, destinationZipPath);
        ...
        out.close(); // Exception if fileCount=0;
        return true;
        // return zipfile;
    } catch (IOException ex) {
        if (out != null) {
            out.close();
        }
        destinationZipPath.toFile().delete(); // Or whatever is appropriate.
        return false;
    }
    

    也许更好的办法是在循环中试一试。以及检查文件的数量

    然后,您可以尝试使用资源