How to Rename Files in Zip Archive Without Extracting and Recompressing Them

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

Zip is an archive format, so mutating generally involves rewriting the file.

Some particular features of zip also get in the way (zip is full of "features"). As well as the central directory at the end of the archive, each component file is preceded by its file name. Zip doesn't have a concept of directories - file names are just strings that happen to include "/" characters (and substrings such as "../".

So, you really need to copy the file using ZipInputStream and ZipOutputStream, renaming as you go. If you really wanted to you could rewrite the file in place doing your own buffering. The process does cause the contents to be recompressed as the standard API has no means of obtaining the data in compressed form.

Edit: @Doval points out that @megasega's answer uses Zip File System Provider in NIO, new (relative to this answer) in Java SE 7. It's performance will likely be not great, as were the archive file systems in RISC OS' GUI of thirty years ago.

DotNetZip - rename file entry in zip file while compressing

From the DotNetZip FAQ:

Add an entry, overriding its name in the archive

  using (ZipFile zip1 = new ZipFile())
{
zip1.AddFile("myFile.txt").FileName = "otherFile.txt";
zip1.Save(archiveName);
}

Renaming zip to match it's contents using PowerShell

This should help you here's a function to get the name of the zip file based on your requirements, just pass it the location of your log files:

function Get-ZipFileName
{
param
($logPath)

# Get a list of files, remove the extension and split on the hyphen, #
# then take the second part of the array
$filenames = gci -Path $logPath -Filter "*.log" | % { $($_.Basename -split "-")[1] }

# Get the first item in the now sorted list
$first = $filenames | Sort-Object | Select-Object -First 1

# Get the first item in the sorted list, now descending to get the last
$last = $filenames | Sort-Object -descending | Select-Object -First 1

# return the filename
"log-{0} - {1}" -f $first, $last
}

I would suggest you look at using a slightly different date format that will sort better, yyyymmdd will sort better than ddmmyyyy.



Related Topics



Leave a reply



Submit