尝试在zip文件中重命名内部文件,而不必以编程方式提取然后重新压缩。
例子。 test.zip包含test.txt,我想更改它,以便test.zip包含newtest.txt(test.txt重命名为newtest.txt,内容保持不变)
遇到了这个有效的链接,但遗憾的是它希望test.txt存在于系统中。在示例中,srcfile应该存在于服务器上。
Blockquote Rename file in zip with zip4j
然后在Linux上的zipnote上使用icame来实现这一诀窍但不幸的是我的版本不适用于文件> 4GB。
有关如何完成此任务的任何建议?特别是在java。
答案 0 :(得分:1)
这应该可以使用Java 7 Zip FileSystem提供程序,例如:
// syntax defined in java.net.JarURLConnection
URI uri = URI.create("jar:file:/directoryPath/file.zip");
try (FileSystem zipfs = FileSystems.newFileSystem(uri, Collections.<String, Object>emptyMap())) {
Path sourceURI = zipfs.getPath("/pathToDirectoryInsideZip/file.txt");
Path destinationURI = zipfs.getPath("/pathToDirectoryInsideZip/renamed.txt");
Files.move(sourceURI, destinationURI);
}
答案 1 :(得分:0)
我使用zip4j修改并重写中央目录部分中的文件头,以避免重写整个zip文件:
ArrayList<FileHeader> FHs = (ArrayList<FileHeader>) zipFile.getFileHeaders();
FHs.get(0).setFileName("namename.mp4");
FHs.get(0).setFileNameLength("namename.mp4".getBytes("UTF-8").length);
zipFile.updateHeaders ();
//where updateHeaders is :
public void updateHeaders() throws ZipException, IOException {
checkZipModel();
if (this.zipModel == null) {
throw new ZipException("internal error: zip model is null");
}
if (Zip4jUtil.checkFileExists(file)) {
if (zipModel.isSplitArchive()) {
throw new ZipException("Zip file already exists. Zip file format does not allow updating split/spanned files");
}
}
long offset = zipModel.getEndCentralDirRecord().getOffsetOfStartOfCentralDir();
HeaderWriter headerWriter = new HeaderWriter();
SplitOutputStream splitOutputStream = new SplitOutputStream(new File(zipModel.getZipFile()), -1);
splitOutputStream.seek(offset);
headerWriter.finalizeZipFile(zipModel, splitOutputStream);
splitOutputStream.close();
}
本地文件头部分的名称字段保持不变,因此该库中将出现不匹配异常。
这很棘手,但可能有问题,我不知道。