在Map代码中添加以下代码,可以获取每条数据所属的文件名
Map代码
package com.czxy.Test03;
import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import java.io.IOException;
public class MoreFileMap extends Mapper {
代码语言:javascript复制@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
//获取所属的文件名称
FileSplit inputSplit = (FileSplit) context.getInputSplit();
String name = inputSplit.getPath().getName();
context.write(new Text(name),value);
}
}
Reduce代码
package com.czxy.Test03;
import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer;
import java.io.IOException;
public class MoreFileReduce extends Reducer {
代码语言:javascript复制@Override
protected void reduce(Text key, Iterable values, Context context) throws IOException, InterruptedException {
for (Text value : values) {
context.write(key,value);
}
}
}
Driver代码
package com.czxy.Test03;
import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner;
public class MoreFileDriver extends Configured implements Tool { @Override public int run(String[] args) throws Exception { Job job = Job.getInstance(new Configuration(),“lineCount”);
代码语言:javascript复制 job.setInputFormatClass(TextInputFormat.class);
TextInputFormat.addInputPath(job,new Path("E:\aaaa.txt")); 文件所在路径
job.setMapperClass(MoreFileMap.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(Text.class);
job.setReducerClass(MoreFileReduce.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(LongWritable.class);
job.setOutputFormatClass(TextOutputFormat.class);
TextOutputFormat.setOutputPath(job,new Path("E:\cccc.txt"));
return job.waitForCompletion(true)?0:1;
}
public static void main(String[] args) throws Exception {
int run = ToolRunner.run(new MoreFileDriver(), args);
}
}
效果:
aaaa.txt
cccc.txt