默认情况下,一个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();
}
}
最后输出结果为: