博主用的是hadoop1.0.4版本。实现多文件及多文件夹输出主要用到MultipleOutputs这个类。这是包路径 org.apache.hadoop.mapreduce.lib.output。偏好用最简单的例子分举例分析如下:
public class WordCount {
public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(Object key, Text value, Context context) throws IOException,
InterruptedException {
StringTokenizer itr = new StringTokenizer(value.toString());
while (itr.hasMoreTokens()) {
word.set(itr.nextToken());
context.write(word, one);
}
}
}
public static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
private MultipleOutputs<Text,IntWritable> mos;
protected void setup(Context context) throws IOException,InterruptedException {
mos = new MultipleOutputs<Text,IntWritable>(context);
}
private IntWritable result = new IntWritable();
public void reduce(Text key, Iterable<IntWritable> values, Context context)
throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
result.set(sum);
//在这里可以灵活的按照自己的想法去输出
// (多文件输出)出现次数大于10和小于10的分别输出在不同的文件
if(sum<10)
mos.write(key, new IntWritable(sum),"summax10");
else
mos.write(key, new IntWritable(sum),"summin10");
// (多文件夹输出)出现次数大于10和小于10的分别输出在不同的文件夹
if(sum<10)
mos.write("11",key, new IntWritable(sum),"summax10/");
else
mos.write("22",key, new IntWritable(sum),"summin10/");
}
protected void cleanup(Context context) throws IOException,InterruptedException {
mos.close();
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
if (otherArgs.length != 2) {
System.err.println("Usage: wordcount <in><out>");
System.exit(2);
}
Job job = new Job(conf, "word count");
job.setJarByClass(WordCount.class);
job.setNumReduceTasks(2);
job.setMapperClass(TokenizerMapper.class);
job.setCombinerClass(IntSumReducer.class);
job.setReducerClass(IntSumReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
//另外就是配置的时候设置如下,需要将不同的文件输出格式添加。
MultipleOutputs.addNamedOutput(job,"11",TextOutputFormat.class,Text.class,IntWritable.class);
MultipleOutputs.addNamedOutput(job,"22",TextOutputFormat.class,Text.class,IntWritable.class);
FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
}
多文件的输入输出在注意在cleanup中调用close()方法不然会报错。
当然此刻也可以使用自己实现的MultipleOutputFormat类,可以参考这位同学的博客