包含三个文件:主文件,mapper文件,reduce文件
主文件:
public class MyWC {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration(true);
Job job = Job.getInstance(conf);
//设置含main方法的类,即本类
job.setJarByClass(MyWC.class);
//设置job运行时的名字
job.setJobName("myjob");
// job.setInputPath(new Path("in"));
// job.setOutputPath(new Path("out"));
//设置map读取文件的位置
Path infile = new Path("/user/root/sxt02.txt");
FileInputFormat.addInputPath(job, infile );
//设置reduce输出的结果文件的位置
Path outfile = new Path("/data/wc/output01");
//输出目录不能存在,存在就删除
if(outfile.getFileSystem(conf).exists(outfile)){
outfile.getFileSystem(conf).delete(outfile,true);
}
FileOutputFormat.setOutputPath(job, outfile );
//设置job运行的mappper类
job.setMapperClass(MyMapper.class);
//设置mapper往reduce输出的序列化和反序列化类型
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(IntWritable.class);
//设置job运行的reduce类
job.setReducerClass(MyReducer.class);
// Submit the job, then poll for progress until the job is complete
job.waitForCompletion(true);
}
mapper文件:
/**
*
* @author Administrator
* Object:偏移量,本行偏移量+本行某个字符在本行的偏移量=本行某个字符在整个文件的偏移量
* Text:一条数据,指的是要读取的文件的一条数据,接下来我们的方法都是对这一行数据做操作
* Text, IntWritable:map输出到磁盘的key和value类型。要与reduce的KEYIN,VALUEIN一致。
*/
public class MyMapper 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());
//遍历这一行数据,用空格或者制表符切割,出现一个字符串就记为1,并输出到磁盘
while (itr.hasMoreTokens()) {
word.set(itr.nextToken());
context.write(word, one);
}
}
}
reduce文件:
/**
*
* @author Administrator
*Text, IntWritable:与mapper的keyout,valueout相同,从磁盘中读取map输出的文件
*Text, IntWritable:定义输出结果的key和value类型
*/
public class MyReducer extends Reducer<Text, IntWritable, Text, IntWritable>{
private IntWritable result = new IntWritable();
//sxt,1
//sxt,1
//sxt,1
//sxt,1
//sxt,1
public void reduce(Text key, Iterable<IntWritable> values,
Context context) throws IOException, InterruptedException {
//key sxt
//values (1,1,1,1,1)
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
result.set(sum);
context.write(key, result);
//sxt 22
}
}