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 extends FileOutputFormat,把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));
      }
    }

你可能感兴趣的:(hadoop)