Mapreduce中文处理策略

hadoop源代码中涉及编码问题时都是写死的utf-8,但是不少情况下,也会遇到输入文件和输出文件需要GBK编码的情况。

GBK编码文件的输入:

(1)输入文件为GBK,则只需在mapper或reducer程序中读取Text时,进行一下转码,以确保都是以UTF-8的编码方式在运行。

// 转码

 Text newText = transformTextToUTF8(value, "GBK");
 String line = newText.toString();

//自定义以下方法

public static Text transformTextToUTF8(Text text, String encoding) {
    String value = null;
    try {
      value = new String(text.getBytes(), 0, text.getLength(), encoding);
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return new Text(value);
  }

(2)输出GBK文件,则重写TextOutputFormat类。

public class GBKFileOutputFormat<K, V> extends FileOutputFormat<K, V>,把TextOutputFormat的源码拷过来,然后把里面写死的utf-8编码改成GBK编码。运行程序时设置:job.setOutputFormatClass(GBKFileOutputFormat.class);

 private static final String utf8 = “UTF-8″;//这里被写死成了utf-8
改为:
 =>private static final String gbk = “gbk”;
private void writeObject(Object o) throws IOException {
      if (o instanceof Text) {
        Text to = (Text) o;
       out.write(to.getBytes(), 0, to.getLength());//这里也需要修改
      } else {
        out.write(o.toString().getBytes(utf8));
      }
    }
=>把writeObject按如下进行修改。
private void writeObject(Object o) throws IOException {
      if (o instanceof Text) {
        out.write(o.toString().getBytes(gbk));
      }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值