【问题标题】:Deleting file inside a zip in java在java中删除zip中的文件
【发布时间】:2017-01-13 09:25:00
【问题描述】:

我有一个包含一些文件的文件夹,现在我想将这些文件附加到一个已经存在的 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 方法是如何工作的,以便我可以尝试找到错误点。

提前致谢

【问题讨论】:

标签: java zip4j


【解决方案1】:

试试这个……!!提供 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");   
        } 
    }

【讨论】:

  • 我曾尝试使用 FileSystems,但无法使其正常工作。它继续发送错误,ReadOnlyFileSystems 异常。可以用 zip4j 提出任何建议,或者如何使这个 FilesSystem 工作。
  • 请分享完整的堆栈跟踪和您尝试过的代码。
  • 使用 java.nio.file.FileSystem 而不是 FilesSystem 或 FileSystems
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
相关资源
最近更新 更多