流程图如下:
WordMap.java
package yiyun.hadoop.wordcount;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class WordMap extends Mapper<Object, Text, Text, IntWritable> {
protected void map(Object key, Text value, Context context)
throws IOException, InterruptedException {
String[] words = value.toString().split(" ");
for(String word : words) {
// 每个单词出现 1 次,作为中间结果输出
context.write(new Text(word), new IntWritable(1));
}
}
}
WordReduce.java
package yiyun.hadoop.wordcount;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
public class WordReduce extends Reducer<Text, IntWritable, Text, IntWritable> {
protected void reduce(Text key, Iterable<IntWritable> values)
throws IOException, InterruptedException {
int sum = 0;
for(IntWritable count : values) {
sum = sum + count.get();
}
// 输出最终结果
context.write(key, new IntWritable(sum));
}
}
WordMain.java
package yiyun.hadoop.wordcount;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
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.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
public class WordMain {
public static void main(String[] args)
throws IOException, ClassNotFoundException, InterruptedException {
if(args.length != 2 || args == null) {
System.out.println("please input current Path");
System.exit(0);
}
Configuration conf = new Configuration();
Job job = new Job(conf, WordMain.class.getSimpleName());
// 打包jar包
job.setJarByClass(WordMain.class);
// 通过job设置输入输出格式
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
// 设置输入输出路径
FileInputFormat.setInputPaths(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
// 设置处理 Map/Reduce 阶段的类
job.setMapperClass(WordMap.class);
job.setReducerClass(WordReduce.class);
// 设置最终输出 key/value 的类型
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
// 提交作业
job.waitForCompletion(true);
}
}
上传 test.txt 到 hadoop 根目录
hadoop fs -put /home/yiyun/test.txt /
查看是否上传成功
hadoop fs -ls /
运行jar包,指定包名及主类名,然后指定输入路径参数和输出路径参数(该参数都是在HDFS上,且输出路径即word文件夹不能够已存在)
hadoop jar /home/yiyun/wordcount.jar yiyun.hadoop.wordcount.WordMain /test.txt /word