MapReducer中自定义OutputFormat

OutputFormat 接口实现类

OutputFormat是MapReduce输出的基类,所有实现MapReduce输出都实现了OutputFormat接口。

  1. 文本输出TextOutputFormat
    默认的输出格式是TextOutputFormat,它把每条记录写为文本行。它的键值可以是任何类型,因为TextOutputFormat调用toString()方法把他们转换为字符串。
  2. SequenceFileOutputFormat
    将SequenceFileOutputFormat输出作为后续MapReduce任务的输入。这是一种好的输出格式,因为它的格式紧凑,容易压缩
  3. 自定义OutputFormat

  • 自定义一个类继承FileOutFormat
  • 重写RecordWriter,具体重写输出数据的方法write();

继承FileOutFormat

 /**
 * 自定义输出格式
 * 如何输出由自己决定, 可以把数据写入到任何地方.
 */
public class LogWriter extends FileOutputFormat<Text, NullWritable> {

    public RecordWriter<Text, NullWritable> getRecordWriter(TaskAttemptContext job) throws IOException, InterruptedException {
		return new FilterRecordWriter(job);
    }

重写RecordWriter

public class FilterRecordWriter extends RecordWriter<Text, NullWritable> {

    private final FSDataOutputStream atguiguOut;
    private final FSDataOutputStream otherOut;

    public FilterRecordWriter(TaskAttemptContext job) throws IOException {
        Configuration conf = job.getConfiguration();
        // 1 获取文件系统
        FileSystem fs = FileSystem.get(conf);
        // 2 创建输出文件路径
        Path atguiguPath = new Path("e:/atguigu.log");
        Path otherPath = new Path("e:/other.log");

        atguiguOut = fs.create(atguiguPath);
        otherOut = fs.create(otherPath);


    }

    @Override
    public void write(Text key, NullWritable value) throws IOException, InterruptedException {
        if (key.toString().contains("atguigu")) {
            atguiguOut.write(key.toString().getBytes());
        } else {
            otherOut.write(key.toString().getBytes());
        }
    }

    @Override
    public void close(TaskAttemptContext context) throws IOException, InterruptedException {
        // 关闭资源
        IOUtils.closeStream(atguiguOut);
        IOUtils.closeStream(otherOut);

    }
}

jobDriver设置

		// 要将自定义的输出格式组件设置到job中
        job.setOutputFormatClass(FilterOutputFormat.class);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值