Search code examples
javazip4j

how to remove file from password protected Zip File using zip4j ? getting exception


Here is My code but it's giving an exception.

net.lingala.zip4j.exception.ZipException: cannot delete old zip file
at net.lingala.zip4j.util.ArchiveMaintainer.restoreFileName(ArchiveMaintainer.java:234)
at net.lingala.zip4j.util.ArchiveMaintainer.initRemoveZipFile(ArchiveMaintainer.java:216)
at net.lingala.zip4j.util.ArchiveMaintainer.removeZipFile(ArchiveMaintainer.java:61)
at net.lingala.zip4j.core.ZipFile.removeFile(ZipFile.java:821)
at net.lingala.zip4j.core.ZipFile.removeFile(ZipFile.java:794)
at com.imimobile.workflow.zip.poc.ZipUtility.removeFileFromZipFile(ZipUtility.java:50)
at com.imimobile.workflow.zip.poc.ProcessExc.main(ProcessExc.java:25)



  public boolean removeFileFromZipFile(String zipFilepath, String filepath) {
    try {
        ZipFile zipFile = new ZipFile(zipFilepath);
        zipFile.removeFile(filepath);
    } catch (ZipException ex) {
        ex.printStackTrace();
        return false;
    }
    return true;
}

this code is working if I'm calling single method Like

removeFileFromZipFile("E:\POC\files\test.zip", "test.html")

it's not working when I'm trying to do below operation like in sequence.

  • reading file from the zip
  • removing file from zip

getFileFromZip("E:\POC\files\test.zip", "test.html") removeFileFromZipFile("E:\POC\files\test.zip", "test.html") // here i'm geting exception

 public String getFileFromZip(String zipPath, String filePath) {
    String data = null;
    ZipInputStream is = null;
    try {
        // Initiate the ZipFile
        ZipFile zipFile = new ZipFile(zipPath);
        if (zipFile.isEncrypted()) {
            zipFile.setPassword("abc@123");
        }

        FileHeader fileHeader = zipFile.getFileHeader(filePath);

        if (fileHeader != null) {
            is = zipFile.getInputStream(fileHeader);
            data = IOUtils.toString(is, StandardCharsets.UTF_8);
            System.out.println("Data :: " + data);
        } else {
            System.err.println("FileHeader does not exist");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return data;
}

Solution

  • Make sure you close the file after creating it, and reopen it before attempting to delete a member. Otherwise the file remains locked and cannot be deleted and recreated during the member delete operation.