Home  >  Article  >  Backend Development  >  Golang read text garbled solution

Golang read text garbled solution

尚
Original
2019-12-04 11:32:315848browse

Golang read text garbled solution

1、当文件中存在中文字符时,读取文件出现乱码,解决方法:(推荐:go视频教程

使用"github.com/axgle/mahonia"第三方包解译码。

package function
import (
	"strings"
	"fmt"
	"io/ioutil"
	"os"
	"github.com/axgle/mahonia"
)
func main() {
	fi, err := os.Open("E:\\goTest\\CommandWindowPrint.txt")
	if err != nil {
		return
	}
   	defer fi.Close()
   	decoder := mahonia.NewDecoder("gbk") // 把原来ANSI格式的文本文件里的字符,用gbk进行解码。
   	fd, err := ioutil.ReadAll(decoder.NewReader(fi))
   	if err != nil {
   		return
   	}
   	ds := strings.Split(string(fd), "\n")
   	fmt.Println("ds", ds)
}

更多golang知识请关注golang教程栏目。

The above is the detailed content of Golang read text garbled solution. 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