renaming file name inside a zip file

廉价感情. 提交于 2019-12-06 23:43:33

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

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..

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