1. GBK转UTF8
1.1. 文件树形图
demo
├── gbk.txt
└── text_test.go
1.2. 代码
gbk.txt
注意使用GBK编码
中国
text_test.go
package main
import (
"bytes"
"golang.org/x/text/encoding/simplifiedchinese"
"golang.org/x/text/transform"
"io/ioutil"
"testing"
)
func TestGBK(t *testing.T) {
data, err := ioutil.ReadFile("gbk.txt")
if err != nil {
t.Fatal(err)
}
// 打印GBK
t.Log(string(data))
// GBK转UTF8
data, err = ioutil.ReadAll(transform.NewReader(bytes.NewBuffer(data), simplifiedchinese.GBK.NewDecoder()))
if err != nil {
t.Fatal(err)
}
// 打印UTF8
t.Log(string(data))
}
1.3. 测试
=== RUN TestGBK
text_test.go:17: �й�
text_test.go:26: 中国
--- PASS: TestGBK (0.00s)
PASS
2. UTF8转GBK
2.1. 文件树形图
demo
├── utf8.txt
└── text_test.go
2.2. 代码
utf8.txt
注意使用utf8编码
中国
text_test.go
package main
import (
"bytes"
"golang.org/x/text/encoding/simplifiedchinese"
"golang.org/x/text/transform"
"io/ioutil"
"testing"
)
func TestUTF8(t *testing.T) {
data, err := ioutil.ReadFile("utf8.txt")
if err != nil {
t.Fatal(err)
}
// 打印UTF8
t.Log(string(data))
// UTF8转GBK
data, err = ioutil.ReadAll(transform.NewReader(bytes.NewBuffer(data), simplifiedchinese.GBK.NewEncoder()))
if err != nil {
t.Fatal(err)
}
// 打印GBK
t.Log(string(data))
}
2.3. 测试
=== RUN TestUTF8
text_test.go:17: 中国
text_test.go:26: �й�
--- PASS: TestUTF8 (0.00s)
PASS