0

我有一个包含一些文件的文件夹,现在我想将这些文件附加到一个已经存在的 zip 中。如果我添加到 zip 中的文件已经存在,那么我将用新文件替换旧文件。对于 zip 操作,我使用的是 zip4j jar。这是我的一段代码

        for(File entry : temp.listFiles())
        {
            String file = entry.getName();

            if(trgZip.getFileHeader(file) != null)
            {
                trgZip.removeFile(file);
            }
            ZipParameters param = new ZipParameters();
            trgZip.addFile(entry, param);
        }

但是我收到了这个异常 net.lingala.zip4j.exception.ZipException: cannot delete old zip file 谁能建议我应该怎么做才能纠正这个问题,或者我哪里出错了,或者这个removeFile方法是如何工作的,所以我可以尝试定位错误点。

提前致谢

4

1 回答 1

0

尝试这个... !!提供 zip 文件的路径作为第一个参数,并提供要从 zip 文件中删除的文件名作为第二个参数。

public static void deleteFile(String zipFilePath,String fileName) throws Exception{
        Map<String, String> zip_properties = new HashMap<>(); 
        zip_properties.put("create", "false"); 

        /* Specify the path to the ZIP File that you want to read as a File System */
        URI zip_disk = URI.create("jar:file:"+zipFilePath);

        /* Create ZIP file System */
        try (FileSystem zipfs = FileSystems.newFileSystem(zip_disk, zip_properties)) {
            /* Get the Path inside ZIP File to delete the ZIP Entry */
            Path pathInZipfile = zipfs.getPath(fileName);
            System.out.println("About to delete an entry from ZIP File" + pathInZipfile.toUri() ); 
            /* Execute Delete */
            Files.delete(pathInZipfile);
            System.out.println("File successfully deleted");   
        } 
    }
于 2017-01-13T10:55:12.437 回答