在java中删除zip中的文件

时间:2017-01-13 09:25:01

标签: java zip4j

我有一个包含一些文件的文件夹,现在我想将这些文件附加到已存在的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:无法删除旧的zip文件 任何人都可以建议我应该怎么做才能纠正这个问题,或者我哪里出错了,或者 removeFile 方法是如何工作的,这样我就可以尝试找出错误点。

提前致谢

1 个答案:

答案 0 :(得分: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");   
        } 
    }
相关问题