美文网首页
Hadoop 处理UTF-8与GBK转化

Hadoop 处理UTF-8与GBK转化

作者: sf705 | 来源:发表于2017-08-11 13:10 被阅读99次

最近在处理一个log时,发现出现乱码,想起来自己要处理的log编码是GB18030,而hadoop默认的编码格式是UTF-8,所以需要转化。在读取数据的时候就是GBK转化为UTF-8,在处理完成后写入结果时,将UTF-8 转化为GBK(我这个log是GB18030)

map输入时,将GB18030转UTF-8

public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
        value = getTextToUTF8(value, "GB18030");// 转码 为UTF-8

而getTextToUTF8函数如下:

public Text getTextToUTF8(Text text, String encoding) {
        String value = null; // Java String 是 Unicode 形式.
        try {
            value = new String(text.getBytes(), 0, text.getLength(), encoding); // text.getBytes()得到的byte数组是原始数据的byte数组,是原始编码.
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new Text(value);
    }

Reduce输出时,将UTF-8转化为 GB18030

在网上找资料的时候,有些网友说在TextOutputFormat将utf-8写死了,如果在Reduce阶段,想将结果编码为GBK,需要重写 TextOutputFormat
但是发现,其实也不需要,直接转化也行的,方法如下

private LongWritable result = new LongWritable();
    public void reduce(Text key, Iterable<LongWritable> values,Context context) throws IOException, InterruptedException {
          long sum = 0;
          for (LongWritable val : values) {
            sum += val.get();
          }
          result.set(sum);
          context.write(new Text(key.toString().getBytes("GB18030")), result);
          //context.write(key, result);
    }

处理完毕,发现结果不是乱码,可见无需重写TextOutputFormat类也行。

参考文献

http://note.youdao.com/share/?id=04678102d70bae8334b26df2c9c4a961&type=note#/

相关文章

网友评论

      本文标题:Hadoop 处理UTF-8与GBK转化

      本文链接:https://www.haomeiwen.com/subject/upvlrxtx.html