企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 注意: 需要下一个转码器,解决乱码问题 [https://github.com/axgle/mahonia](https://github.com/axgle/mahonia) 安装: ~~~ go get github.com/axgle/mahonia ~~~ ## 一、实例 注意:这里文件001.txt是以读取,每行数据中不同类型数据以,分割 例: a1,623023199903081812,M,上海 a2,623023199903081812,M,上海 a3,623023199999903081812,M,上海 a4,623023199903081812,M,上海 ~~~ package main import ( "io/ioutil" "fmt" "strings" "github.com/axgle/mahonia" "os" "bufio" "io" ) func main() { //read 和 read2 的区别:read没有使用缓冲 read2 使用了缓冲 //read() read2() } func read() { contentBytes, err := ioutil.ReadFile("G:\\pachong\\001.txt") if err != nil { fmt.Println("读入失败", err) } //转字符串 contentStr := string(contentBytes) //逐行打印 //按行分割 lineStrs := strings.Split(contentStr, "\n\r") for _, lineStr := range lineStrs { //fmt.Println(lineStr) //转码 newStr := ConvertEncoding(lineStr, "GBK") fmt.Println(newStr) } } //处理乱码 func ConvertEncoding(srcStr string, encoding string) (dstStr string) { enc := mahonia.NewDecoder(encoding) utfStr := enc.ConvertString(srcStr) dstStr = utfStr return } //缓冲读 func read2() { //打开文件 file, _ := os.Open("G:\\pachong\\001.txt") //关闭资源 defer file.Close() //新建一个缓冲区,把内容先放到缓冲区 reader := bufio.NewReader(file) //循环 for { lineBytes, _, err := reader.ReadLine() if err == io.EOF { break } gbkStr := string(lineBytes) newStr := ConvertEncoding(gbkStr, "GBK") fmt.Println(newStr) } } ~~~