search
HomeBackend DevelopmentGolangHow 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 languageUnzipFile 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
    }
}

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

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

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

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
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
The Performance Race: Golang vs. CThe Performance Race: Golang vs. CApr 16, 2025 am 12:07 AM

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

Golang vs. C  : Code Examples and Performance AnalysisGolang vs. C : Code Examples and Performance AnalysisApr 15, 2025 am 12:03 AM

Golang is suitable for rapid development and concurrent programming, while C is more suitable for projects that require extreme performance and underlying control. 1) Golang's concurrency model simplifies concurrency programming through goroutine and channel. 2) C's template programming provides generic code and performance optimization. 3) Golang's garbage collection is convenient but may affect performance. C's memory management is complex but the control is fine.

Golang's Impact: Speed, Efficiency, and SimplicityGolang's Impact: Speed, Efficiency, and SimplicityApr 14, 2025 am 12:11 AM

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

C   and Golang: When Performance is CrucialC and Golang: When Performance is CrucialApr 13, 2025 am 12:11 AM

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang in Action: Real-World Examples and ApplicationsGolang in Action: Real-World Examples and ApplicationsApr 12, 2025 am 12:11 AM

Golang excels in practical applications and is known for its simplicity, efficiency and concurrency. 1) Concurrent programming is implemented through Goroutines and Channels, 2) Flexible code is written using interfaces and polymorphisms, 3) Simplify network programming with net/http packages, 4) Build efficient concurrent crawlers, 5) Debugging and optimizing through tools and best practices.

Golang: The Go Programming Language ExplainedGolang: The Go Programming Language ExplainedApr 10, 2025 am 11:18 AM

The core features of Go include garbage collection, static linking and concurrency support. 1. The concurrency model of Go language realizes efficient concurrent programming through goroutine and channel. 2. Interfaces and polymorphisms are implemented through interface methods, so that different types can be processed in a unified manner. 3. The basic usage demonstrates the efficiency of function definition and call. 4. In advanced usage, slices provide powerful functions of dynamic resizing. 5. Common errors such as race conditions can be detected and resolved through getest-race. 6. Performance optimization Reuse objects through sync.Pool to reduce garbage collection pressure.

Golang's Purpose: Building Efficient and Scalable SystemsGolang's Purpose: Building Efficient and Scalable SystemsApr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Apr 02, 2025 pm 05:24 PM

Confused about the sorting of SQL query results. In the process of learning SQL, you often encounter some confusing problems. Recently, the author is reading "MICK-SQL Basics"...

See all articles

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool