golang 实现解压

发布时间:2024-07-05 00:02:33

使用Golang实现解压文件

在开发过程中,我们经常会遇到需要解压文件的情况。Golang提供了一些方便的库和函数,可以轻松实现文件的解压操作。

使用Zip库解压文件

Golang的archive/zip包提供了对zip文件格式的支持。下面是一个解压zip文件的示例代码:

```go package main import ( "archive/zip" "fmt" "io" "os" "path/filepath" ) func unzipFile(zipPath string, destPath string) error { r, err := zip.OpenReader(zipPath) if err != nil { return err } defer r.Close() for _, f := range r.File { err := extractAndWriteFile(f, destPath) if err != nil { return err } } return nil } func extractAndWriteFile(f *zip.File, destPath string) error { rc, err := f.Open() if err != nil { return err } defer rc.Close() path := filepath.Join(destPath, f.Name) if f.FileInfo().IsDir() { err = os.MkdirAll(path, f.Mode()) if err != nil { return err } } else { err = os.MkdirAll(filepath.Dir(path), 0755) if err != nil { return err } f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode()) if err != nil { return err } defer f.Close() _, err = io.Copy(f, rc) if err != nil { return err } } return nil } func main() { zipPath := "path/to/your/archive.zip" destPath := "path/to/destination" err := unzipFile(zipPath, destPath) if err != nil { fmt.Println("Failed to unzip file:", err) } else { fmt.Println("File unzipped successfully!") } } ```

使用Tar库解压文件

Golang的archive/tar包提供了对tar文件格式的支持。下面是一个解压tar文件的示例代码:

```go package main import ( "archive/tar" "fmt" "io" "os" "path/filepath" ) func untarFile(tarPath string, destPath string) error { f, err := os.Open(tarPath) if err != nil { return err } defer f.Close() tr := tar.NewReader(f) for { header, err := tr.Next() if err == io.EOF { break } if err != nil { return err } path := filepath.Join(destPath, header.Name) info := header.FileInfo() if info.IsDir() { err = os.MkdirAll(path, info.Mode()) if err != nil { return err } } else { err = os.MkdirAll(filepath.Dir(path), 0755) if err != nil { return err } f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, info.Mode()) if err != nil { return err } defer f.Close() _, err = io.Copy(f, tr) if err != nil { return err } } } return nil } func main() { tarPath := "path/to/your/archive.tar" destPath := "path/to/destination" err := untarFile(tarPath, destPath) if err != nil { fmt.Println("Failed to untar file:", err) } else { fmt.Println("File untarred successfully!") } } ```

总结

Golang提供了方便易用的库和函数,可以轻松实现文件的解压操作。通过使用archive/zip包和archive/tar包,我们可以分别解压zip和tar文件。以上示例代码可以作为参考,帮助你在Golang中实现文件解压功能。

相关推荐