改变reduce输出文件名字的方法

默认情况下,一个reducer产生一个文件,以name-r-nnnnn来命名,其中默认的name为part,nnnnn从(00000开始递增),保证了每个reducer不会产生重复的文件。
这里写图片描述
如果想要更改输出文件的name,可以使用MultipleOutput类,它允许将数据写到多个文件,这些文件的名字来源于输入的key、value或任意字符串。在reduce()中使用MultipleOutput.write()来写输出。
这里写图片描述
参数含义分别为:键、值、文件输出的基本路径。其中文件输出的基本路径是相对于输出路径来解释的。如输出路径设置为/weather/out,则文件的最终路径保存为/weather/out/baseOutputPath

package com.summerzhou.mapreduce;

import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;

public class MaxTempReduce extends Reducer<Text, IntWritable, Text, IntWritable> {
    private MultipleOutputs<Text, IntWritable> multipleOutputs;
    //初始化MultipleOutputs
    @Override
    protected void setup(Reducer<Text, IntWritable, Text, IntWritable>.Context context)
            throws IOException, InterruptedException {
        // TODO Auto-generated method stub
        multipleOutputs = new MultipleOutputs<Text, IntWritable>(context);
    }
    @Override
    protected void reduce(Text key, Iterable<IntWritable> values, Context context)
            throws IOException, InterruptedException {
        int max_temperature = Integer.MIN_VALUE;
        for(IntWritable value:values) {
            int temp = value.get();
            max_temperature = temp > max_temperature?temp:max_temperature;
        }
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
        //输出的实际路径为:/outPath/yyyy-mm-dd/temperature-r-nnnnn
        String basePath = simpleDateFormat.format(date).toString()+"/temperature";
        //替代context输出数据
        multipleOutputs.write(key, new IntWritable(max_temperature), basePath);
    }
    @Override
    protected void cleanup(Reducer<Text, IntWritable, Text, IntWritable>.Context context)
            throws IOException, InterruptedException {
        multipleOutputs.close();
    }
}

最后输出结果为:
这里写图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值