renaming file name inside a zip file

那年仲夏 提交于 2020-02-02 10:22:11

问题


trying to rename internal file within a zip file without having to extract and then re-zip programatically.

example. test.zip contains test.txt, i want to change it so that test.zip will contain newtest.txt(test.txt renamed to newtest.txt, contents remain the same)

came across this link that works but unfortunately it expects test.txt to exist on the system. In the example the srcfile should exist on the server.

Blockquote Rename file in zip with zip4j

Then icame across zipnote on Linux that does the trick but unfortunately the version i have doesnt work for files >4GB.

Any suggestions on how to accomplish this? prefereably in java.


回答1:


This should be possible using Java 7 Zip FileSystem provider, something like:

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



回答2:


Using zip4j, I am modifying and re-writing the file headers inside of the central directory section to avoid rewriting the entire zip file:

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

The name field in the local file header section remains unchanged, so there will be a mismatch exception in this library.
It's tricky but maybe problematic, I don't know..



来源:https://stackoverflow.com/questions/28126450/renaming-file-name-inside-a-zip-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!