0

I'm trying to edit the contents of an odt file using zip4j (I tried using java ZipEntries but I couldn't even delete the entries from the file itself that's why I chose to use a library instead). I can confirm that the file I am trying to overwrite exits I can even read from it and tell when it was created so that part works. Now when I'm trying to edit the odt contents (removing or overwriting) Zip4j throws a ZipException which says: cannot rename modified zip file. What am I doing wrong?

 try
 {
      File temp = new File(f.getParent()+"/tmp/content.xml");
      new File(temp.getParent()).mkdirs();
      FileUtils.write(temp, "", encoding);
      net.lingala.zip4j.ZipFile zf = new net.lingala.zip4j.ZipFile(f.getPath());
      ZipParameters p = new ZipParameters();
      p.setEncryptionMethod(EncryptionMethod.NONE);
      p.setOverrideExistingFilesInZip(true);
      p.setFileNameInZip("content.xml");
      p.setCompressionMethod(CompressionMethod.DEFLATE);
      zf.addFile(temp, p);
 }
 catch (Exception e)
 {
      e.printStackTrace();
 }
Clio Orgyán
  • 300
  • 1
  • 8
  • A zip file system with standard java SE is also possible. – Joop Eggen Feb 04 '20 at 14:59
  • That unfortunately didn't work. I encountered the same problems as I mentioned above. I am able to read but it seems like there is no way I could modify the contents. – Clio Orgyán Feb 04 '20 at 15:18

1 Answers1

1

The zip file system with its jar:file: protocol is supported by Path & Files. A Path maintains its FileSystem, so one can use all operations.

    Path osPath = Paths.get("C:/ ... .odt");
    URI uri = URI.create("jar:" + osPath.toUri());

    Map<String, String> env = new HashMap<>();
    env.put("create", "true");
    try (FileSystem zipFS = FileSystems.newFileSystem(uri, env)) {
        Files.copy(zipFS.getPath("/media/image1.png"), osPath.resolveSibling("image1.png"),
            StandardCopyOption.REPLACE_EXISTING);
        Files.move(zipFS.getPath("/media/image2a.png"), zipFS.getPath("/media/image2.png"));
    }
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • I would like to copy a file inside the odt from an external source. This extracts the file from the odt. I swapped the parameters and corrected the source of the external one but it still doesn't work. Nothing happens not even with Files.delete(). I can still read the contents though. I don't know if it's a permission issue but I can edit the contents with 7-zip so I don't think it would be. – Clio Orgyán Feb 05 '20 at 08:28
  • I succeeded copying an external file into the zip, to a pristine file and overwriting an existing one. Under Windows, Oracle SDK. – Joop Eggen Feb 05 '20 at 10:05
  • Maybe a temp zip file or directory tree is created, without having rights. The same problem as for zip4j. Maybe try to create and fill a temp directory. – Joop Eggen Feb 05 '20 at 10:36