如何解压缩单个文件? [英] How to unzip a single file?

查看:83
本文介绍了如何解压缩单个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了很多有关如何从.zip中提取 all 文件的示例,但是我不知道如何在不迭代.zip文件中的所有文件的情况下提取单个文件

I've found lots of examples on how to extract all files from .zip, but I can't figure out how to extract a single file without iterating over all files in the .zip file.

在Go中是否可以从.zip存档中提取单个文件而无需遍历.zip文件中的所有文件?

Is it possible in Go to extract a single file from a .zip archive without iterating over all files in the .zip file?

例如,如果包含一个zip文件:

For example, if a zip file contained:

folder1/file1.txt
folder1/file2.txt
folder1/file3.txt
folder2/file1.txt

我如何仅提取 folder2/file1.txt ?

推荐答案

zip.Reader 为您提供存档的内容,这些文件为 slice (

zip.Reader provides you the content of the archive, the files as a slice (of zip.File). There is no helper method to get a file by name, you have to iterate over the files with a loop. You don't need to open / extract the files, but to find a file by name, you have to use a loop.

例如:

r, err := zip.OpenReader("testdata/readme.zip")
if err != nil {
    log.Fatal(err)
}
defer r.Close()

for _, f := range r.File {
    if f.Name != "folder2/file1.txt" {
        continue
    }

    // Found it, print its content to terminal:
    rc, err := f.Open()
    if err != nil {
        log.Fatal(err)
    }
    _, err = io.Copy(os.Stdout, rc)
    if err != nil {
        log.Fatal(err)
    }
    rc.Close()
    fmt.Println()
    break
}

这篇关于如何解压缩单个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆