簡體   English   中英

如何在golang中壓縮字符串並返回字節數組

[英]How to gzip string and return byte array in golang

我的 java 代碼如下:

    public static byte[] gzip(String str) throws Exception{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gos = new GZIPOutputStream(baos);
    gos.write(str.getBytes("UTF-8"));
    gos.close();
    return baos.toByteArray();
}

我的 java 完成后,如何在 golang 中壓縮字符串並返回字節數組?

這是使用標准庫compress/gzipgzipString function 的完整示例

package main

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

func gzipString(src string) ([]byte, error) {
    var buf bytes.Buffer
    zw := gzip.NewWriter(&buf)

    _, err := zw.Write([]byte(src))
    if err != nil {
        return nil, err
    }

    if err := zw.Close(); err != nil {
        return nil, err
    }

    return buf.Bytes(), nil
}

func main() {
    gzippedBytes, err := gzipString("")
    if err != nil {
        panic(err)
    }
    fmt.Printf("Zipped out: %v", gzippedBytes)
}

看看下面的代碼片段。 Playgorund: https://play.golang.org/p/3kXBmQ-c9xE

Golang 的標准庫中包含所有內容。 檢查https://golang.org/pkg/compress/gzip

package main

import (
    "bytes"
    "compress/gzip"
    "fmt"
    "log"
    "strings"
    "io"
)

func main() {
    s := "Hello, playground"

    // Create source reader
    src := strings.NewReader(s)

    buf := bytes.NewBuffer(nil)

    // Create destination writer
    dst := gzip.NewWriter(buf)

    // copy the content as gzip compressed
    _, err := io.Copy(dst, src)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(buf.String())
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM