0

I have a folder which contains some files, now I want to append these files to a zip which already exists. If the file I am adding to the zip is already there, then I am replacing the old file with the new one. For zip operations I am using zip4j jar. This is the piece of my code

        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);
        }

But I am getting this exception net.lingala.zip4j.exception.ZipException: cannot delete old zip file can anyone please suggest what should I do to correct this, or where I am going wrong, or how does this removeFile method works, so that I can try locate the point of error.

Thanks in advance

sayan-bose
  • 11
  • 1
  • 2
  • 1
    Possible duplicate of [Delete files from a ZIP archive without Decompressing in Java or maybe Python](http://stackoverflow.com/questions/5244963/delete-files-from-a-zip-archive-without-decompressing-in-java-or-maybe-python) – Raedwald Jan 13 '17 at 09:34

1 Answers1

0

Try this... !! Provide path to you zip file as first argument and filename which you want to delete from zip file as your second argument.

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");   
        } 
    }
Varun Chawla
  • 303
  • 1
  • 6
  • 19
  • I have tried using FileSystems, but I was not being able to make it work. It kept on sending the error, **ReadOnlyFileSystems** Exception. Can suggest anything with zip4j, or how to make this FilesSystem thing work. – sayan-bose Jan 16 '17 at 10:45
  • Please share the full stack trace and the code you have tried. – Varun Chawla Jan 24 '17 at 14:17
  • Use **java.nio.file.FileSystem** not FilesSystem or FileSystems – Varun Chawla Jan 24 '17 at 14:20