主方法:
package com.bjsxt.sn;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider.Text;
public class TestMapReduce {
public static void main(String[] args) throws Exception {
Configuration conf=new Configuration();
Job job=Job.getInstance(conf);
job.setJarByClass(TestMapReduce.class);
job.setJobName("ooxx");
Path fileIn=new Path("/user/root/test.txt");
FileInputFormat.addInputPath(job, fileIn);
Path fileout=new Path("/data/wc/output01");
if(fileout.getFileSystem(conf).exists(fileout)) {
fileout.getFileSystem(conf).delete(fileout,true);
}
FileOutputFormat.setOutputPath(job, fileout);
job.setMapperClass(MyMapper.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(IntWritable.class);
job.setReducerClass(Reducer.class);
job.waitForCompletion(true);
}
}
map方法:
package com.bjsxt.sn;
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
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());
while(itr.hasMoreTokens()) {
word.set(itr.nextToken());
context.write(word, one);
}
}
}
reduce方法:
package com.bjsxt.sn;
import java.io.IOException;
import java.util.Iterator;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
public class Reducer extends org.apache.hadoop.mapreduce.Reducer<Text, IntWritable, Text, IntWritable>{
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();
}
Iterator<IntWritable> it=values.iterator();
while(it.hasNext()) {
IntWritable n=it.next();
System.out.println(n);
System.out.println(key);
}
result.set(sum);
context.write(key, result);
}
}
提交命令:
查看: