Renaming a File/Folder inside a Zip File in Java?

后端 未结 4 1014
小鲜肉
小鲜肉 2020-12-19 17:49

I have a zip file containing a folder structure like

  • main-folder/
    • subFolder1/
    • subFolder2/
    • subFolder3/
      • file3.1
      • fi
4条回答
  •  悲&欢浪女
    2020-12-19 18:08

    I know you asked about Java but just for archival purposes I thought I would contribute a note about .NET.

    DotNetZip is a .NET library for zip files that allows renaming of entries. As Tom Hawtin's reply states, directories are not first-class entities in the zip file metadata, and as a result, no zip libraries that I know of expose a "rename directory" verb. But some libraries allow you to rename all the entries that have names that indicate a particular directory, which gives you the result you want.

    In DotNetZip, it would look like this:

     var regex = new Regex("/OldDirName/.*$");
     int renameCount= 0;
     using (ZipFile zip = ZipFile.Read(ExistingZipFile))
     {
        foreach (ZipEntry e in zip)
        {
            if (regex.IsMatch(e.FileName))
            {
                // rename here
                e.FileName = e.FileName.Replace("/OldDirName/", "/NewDirName/");
                renameCount++;
            }
        }
        if (renameCount > 0)
        {
            zip.Comment = String.Format("This archive has been modified. {0} entries have been renamed.", renameCount);
            // any changes to the entries are made permanent by Save()
            zip.Save();  // could also save to a new zip file here
        }
     }
    

    You can also add or remove entries, inside the using clause.

    If you save to the same file, then DotNetZip rewrites only the changed metadata - the entry headers and the central directory records for renamed entries, which saves time with large archives. If you save to a new file or stream, then all of the zip data gets written.

提交回复
热议问题