Driver
package MapReducer.wordcount
import org.apache.hadoop.fs.Path
import org.apache.hadoop.io.IntWritable
import org.apache.hadoop.io.Text
import org.apache.hadoop.mapreduce.Job
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat
public class WordCountDriver {
public static void main(String[] args) throws Exception{
String inputPath = "/test_wordcount"
String outPath = "/out1"
Job job = Job.getInstance()
job.setJarByClass(WordCountDriver.class)
job.setJobName("wordcount")
job.setMapperClass(WordCountMapper.class)
job.setReducerClass(WordCountReducer.class)
FileInputFormat.addInputPath(job, new Path(inputPath))
FileOutputFormat.setOutputPath(job, new Path(outPath))
job.setMapOutputKeyClass(Text.class)
job.setMapOutputValueClass(IntWritable.class)
job.setOutputKeyClass(Text.class)
job.setOutputValueClass(IntWritable.class)
boolean waitForCompletion = job.waitForCompletion(true)
System.out.println(waitForCompletion)
}
}
MapReducer
package MapReducer.wordcount;
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
/** * 通过map阶段进行单词分割 * <v1,k1>---ConText<v2,k2> * @author HYT * */
public class WordCountMapper extends Mapper<Object, Text, Text, IntWritable> {
@Override
protected void map(Object key, Text value, Context context)
throws IOException, InterruptedException {
String line = value.toString();
if(StringUtils.isNotBlank(line)) {
String[] words = line.split(",");
if(words!=null&&words.length!=0) {
for(String word:words) {
if(StringUtils.isNotBlank(word)) {
Text wordkey = new Text(word);
IntWritable tmpValue = new IntWritable(1);
context.write(wordkey, tmpValue);
}
}
}
}
}
}
Reducer
package MapReducer.wordcount;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
/** * 将<v2,k2>导入进行排序生成<v3,k3> * 输出<v4,k4> * @author HYT * */
public class WordCountReducer extends Reducer<Text,IntWritable,Text,IntWritable> {
@Override
protected void reduce(Text value, Iterable<IntWritable> key,
Reducer<Text, IntWritable, Text, IntWritable>.Context context) throws IOException, InterruptedException {
int sum=0;
for(IntWritable tmpNum:key) {
sum+=tmpNum.get();
}
context.write(value, new IntWritable(sum));
}
}