首先导入包
"code.google.com/p/mahonia"
可以通过此链接获得此包
https://code.google.com/p/mahonia/
参考代码如下:
packagemain import( "bufio" "code.google.com/p/mahonia" "log" "os" "strings" "time" ) funcmain(){ //创建日志文件 t:=time.Now() filepath:="./log_"+strings.Replace(t.String()[:19],":","_",3)+".txt" file,err:=os.OpenFile(filepath,os.O_CREATE,0666) iferr!=nil{ log.Fatal("createlogfileFailed!") } deferfile.Close() wFile:=bufio.NewWriter(file) wFile.WriteString(readfile()) wFile.Flush() } funcreadfile()string{ f,err:=os.Open("ex7.txt") iferr!=nil{ returnerr.Error() } deferf.Close() buf:=make([]byte,1024) //文件ex7.txt的编码是gb18030 decoder:=mahonia.NewDecoder("gb18030") ifdecoder==nil{ return"编码不存在!" } varstrstring="" for{ n,_:=f.Read(buf) if0==n{ break } //解码为UTF-8 str+=decoder.ConvertString(string(buf[:n])) } returnstr }原文链接:https://www.f2er.com/go/191086.html