Home Backend Development Golang How to use Go language to compress and decompress files?

How to use Go language to compress and decompress files?

Jun 09, 2023 pm 09:31 PM
go language Unzip File compression

With the continuous development of computer technology, file processing has become an essential part of computer users' daily work. As the amount of file storage continues to increase, compressing files has become a very necessary operation. In this process, using Go language for file compression and decompression has become a topic of great concern.

The Go language itself provides a rich standard library, which includes related tool functions for processing file operations. Because of this, file compression and decompression operations using Go language are very simple compared to other languages. This article will introduce how to use Go language for file compression and decompression.

1. File compression

Go language has two ways to compress files: using the standard library for file compression and using third-party libraries for file compression.

  1. Use the standard library for file compression

In Go's standard library, there is a "compress" package, which contains implementations of common file compression formats, including gzip, gzip, bz2, lzma, zstd, etc. Implementations of these compression formats are packaged in different subpackages within the "compress" package. Different subpackages implement different compression formats. The specific implementation is as follows:

package main

import (
    "compress/gzip"
    "fmt"
    "os"
)

func main() {
    f, err := os.Create("test.txt.gz")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer f.Close()

    gz := gzip.NewWriter(f)
    defer gz.Close()

    _, err = gz.Write([]byte("hello, world!"))
    if err != nil {
        fmt.Println(err)
        return
    }
}
Copy after login

In the above code, we created a compressed file named "test.txt.gz" and wrote the string "hello, world!" into it. . The entire process uses the "NewWriter" function and the "Write" function in the gzip subpackage. It should be noted that after operating the file, you need to use the defer keyword to close the file, otherwise the file handle may leak.

  1. Use third-party libraries for file compression

Compared with the standard library, the third-party library provides more implementations of file compression formats and more flexibility . Common third-party libraries include "zip" and "rar". These libraries are used in the same way as the standard library, except that the imported package names are different. Take the "zip" package as an example:

package main

import (
    "archive/zip"
    "fmt"
    "os"
)

func main() {
    f, err := os.Create("test.zip")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer f.Close()

    zw := zip.NewWriter(f)
    defer zw.Close()

    files := []struct {
        name, body string
    }{
        {"test.txt", "hello, world!"},
    }

    for _, file := range files {
        w, err := zw.Create(file.name)
        if err != nil {
            fmt.Println(err)
            return
        }
        _, err = w.Write([]byte(file.body))
        if err != nil {
            fmt.Println(err)
            return
        }
    }
}
Copy after login

In the above code, we create a compressed file named "test.zip" and add a file named "test.txt" to it file and wrote the string "hello, world!" to it. This process is implemented using the "NewWriter" function and "Create" function in the "zip" package.

2. File decompression

Go language provides multiple packages related to file compression, thereby realizing the decompression function of files in various formats. The basic process of decompression is:

  1. Open the compressed file.
  2. Create the corresponding read-in stream.
  3. Create the corresponding decompressor.
  4. Write the data read into the stream to the decompressor and output it.
  5. Close files and other resources.
  6. Use the standard library for file decompression

The "compress" package in the standard library implements decompression of multiple compression formats, and the previous gzip library is one example. In other words, it not only supports file compression, but also has the function of file decompression. The specific method is as follows:

package main

import (
    "compress/gzip"
    "fmt"
    "io"
    "os"
)

func main() {
    f, err := os.Open("test.txt.gz")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer f.Close()

    gz, err := gzip.NewReader(f)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer gz.Close()

    data := make([]byte, 1024)
    for {
        n, err := gz.Read(data)
        if err != nil && err != io.EOF {
            fmt.Println(err)
            return
        }
        if n == 0 {
            break
        }
        fmt.Print(string(data[:n]))
    }
}
Copy after login

In the above code, we first open a compressed file named "test.txt.gz", and then use the "NewReader" function in the gzip sub-package to create a decompressed device. The "Read" function reads the data to be output in the decompressor, then assigns it to "data" and outputs it through the "fmt.Print" function.

  1. Use third-party libraries for file decompression

Using third-party libraries for file decompression is similar to file compression. You only need to import the decompression library corresponding to the corresponding file format. . Take the "zip" package as an example:

package main

import (
    "archive/zip"
    "fmt"
    "io"
    "os"
)

func main() {
    r, err := zip.OpenReader("test.zip")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer r.Close()

    for _, f := range r.File {
        rc, err := f.Open()
        if err != nil {
            fmt.Println(err)
            return
        }
        defer rc.Close()

        _, err = io.CopyN(os.Stdout, rc, int64(f.UncompressedSize64))
        if err != nil {
            fmt.Println(err)
            return
        }
    }
}
Copy after login

In the above code, we first use the "OpenReader" function in the "zip" package to open a compressed file named "test.zip" and then read in List of files in it. The "Open" function returns an "io.ReadCloser" interface type, which represents an open file. We can use the "Read" function of this interface type to read the decompressed data, and then output it directly through the "io.CopyN" function.

Summary

As can be seen from the above introduction, the process of using Go language to compress and decompress files is very simple and can be implemented using standard libraries and third-party libraries. Of course, there will also be certain performance differences and format differences between compressed and decompressed files, which require developers to make trade-offs and choices. However, in general, the Go language is very convenient to use and can meet most application needs.

The above is the detailed content of How to use Go language to compress and decompress files?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

Why is it necessary to pass pointers when using Go and viper libraries? Why is it necessary to pass pointers when using Go and viper libraries? Apr 02, 2025 pm 04:00 PM

Go pointer syntax and addressing problems in the use of viper library When programming in Go language, it is crucial to understand the syntax and usage of pointers, especially in...

See all articles