golang读取文件编码转换问题
发布时间:2020-12-16 18:55:53 所属栏目:大数据 来源:网络整理
导读:首先导入包 "code.google.com/p/mahonia" 可以通过此链接获得此包 https://code.google.com/p/mahonia/ 参考代码如下: packagemainimport("bufio""code.google.com/p/mahonia""log""os""strings""time")funcmain(){//创建日志文件t:=time.Now()filepath:=".
首先导入包 "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 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |