How to check if zip entry is directory in Go language

huangapple go评论75阅读模式
英文:

How to check if zip entry is directory in Go language

问题

我猜测在下面的结构中,某个位标记了文件为目录。但是我找不到对此的引用。

http://golang.org/pkg/archive/zip/#FileHeader

英文:

I guess some bit in following structure is marking file as directory.
But I can't find reference to that.

http://golang.org/pkg/archive/zip/#FileHeader

答案1

得分: 7

zip包的FileHeader类型具有你提供的链接,它有一个.FileInfo()方法,该方法返回一个os.FileInfo类型,而该类型本身具有一个.IsDir()方法。

因此,将它们链接在一起,你可以使用f.FileInfo().IsDir()来判断zip归档中的文件是否为目录。

示例代码:

package main

import (
    "archive/zip"
    "fmt"
)

func main() {
    // 打开一个zip归档文件进行读取。
    r, err := zip.OpenReader("example.zip")
    if err != nil {
        fmt.Println(err)
    }
    defer r.Close()

    // 遍历归档文件中的文件,并指示它是否为目录。
    for _, f := range r.File {
        fmt.Printf("%s 是目录吗?- %v\n", f.Name, f.FileInfo().IsDir())
    }
}

希望对你有帮助!

英文:

The zip package's FileHeader type, which you linked to, has a .FileInfo() method which returns an os.FileInfo type, which itself has an .IsDir() method.

So chaining that all together, you can tell if the file in the zip archive is a directory with f.FileInfo().IsDir().

Example:

package main

import (
    "archive/zip"
    "fmt"
)

func main() {
    // Open a zip archive for reading.
    r, err := zip.OpenReader("example.zip")
    if err != nil {
        fmt.Println(err)
    }
    defer r.Close()

    // Iterate through the files in the archive,
    // indicating if it is a directory.
    for _, f := range r.File {
        fmt.Printf("%s is directory? - %v\n", f.Name, f.FileInfo().IsDir())
    }
}

huangapple
  • 本文由 发表于 2014年4月18日 23:28:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/23157226.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定