在路上go笔记-1 使用iconv-go将GB2312编码文件转UTF8

2018-03-25 19:36:07 admin ...

在实际项目中,遇到将GB2312编码文件转为UTF8编码的文件,下面介绍使用iconv-go工具包来完成需求,当然,iconv-go还支持其他编码转换,如windows-1252,latin1,GBK(GB2312的扩展)等编码。

一、安装

安装的方法主要使用“go get”,支持默认路径$GOPATH/bin

go get github.com/djimenez/iconv-go

二、使用

使用的软件包,你需要适当的导入语句:

import (
        iconv "github.com/djimenez/iconv-go"
)

三、转换字符串可以用两种方法完成

1、单次使用

func ConvertString(input string, fromEncoding string, toEncoding string) (output string, err error)

示例:

output,err:= iconv.ConvertString("Hello World!", "utf-8", “GB2312")

2、多次使用

converter := iconv.NewConverter("utf-8", "GB2312")
output,err := converter.ConvertString("Hello World!")
// converter can then be closed explicitly
// this will also happen when garbage collected
converter.Close()

四、转化[]byte数据

in := []byte("Hello World!")
out := make([]byte, len(input))
bytesRead, bytesWritten, err := iconv.Convert(in, out, "utf-8", "GB2312”)

当然也可以仿照字符串的使用方法多次使用

converter := iconv.NewConverter("utf-8", "GB2312")
bytesRead, bytesWritten, error := converter.Convert(input, output)

五、转化io.reader

// We're wrapping stdin for simplicity, but a File or network reader could
// be wrapped as well
reader,_ := iconv.NewReader(os.Stdin, "utf-8", "GB2312”)

六、转化io.writer

// We're wrapping stdout for simplicity, but a File or network reader could
// be wrapped as well
writer,_ := iconv.NewWriter(os.Stdout, "utf-8", “GB2312")

相似文章