直接上代码:
package main.java;
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class WordCount {
// static {
// try {
// // 设置 HADOOP_HOME 目录
// System.setProperty("hadoop.home.dir", "E:\\spark\\anzhuangsoft\\hadoop-2.7.5");
// // 加载库文件
// System.load("E:\\spark\\anzhuangsoft\\hadoop-2.7.5\\bin\\hadoop.dll");
// } catch (UnsatisfiedLinkError e) {
// System.err.println("Native code library failed to load.\n" + e);
// System.exit(1);
// }
// }
//静态内部类(静态内部类只能访问外部类的静态成员)
public static class WordCountMapper extends Mapper<LongWritable, Text, Text,IntWritable>{
// #2
private Text mapOutPutKey=new Text();
private final static IntWritable mapOutPutValue = new IntWritable(1);
@Override
protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, IntWritable>.Context context)
throws IOException, InterruptedException {
// #1 方式1
// String [] words = value.toString().split(" ");//直接split性能较低,或参考
// for (String word : words) {
// context.write(new Text(word), new IntWritable(1));
// }
// #2 方式2 效率高
StringTokenizer stringTokenizer = new StringTokenizer(value.toString());
while(stringTokenizer.hasMoreTokens()){
String wordValue = stringTokenizer.nextToken();
mapOutPutKey.set(wordValue);
context.write(mapOutPutKey,mapOutPutValue);
}
}
}
public static class WordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
// 注意 reduce的输入类型是个迭代器 Iterable<IntWritable> value,因为map将分组后的数据传过来,map会做group,将相同key的value合并在一起,放到一个集合中,如<hadoop,list(1,1,...)>
@Override
protected void reduce(Text key, Iterable<IntWritable> values,Context context) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable intWritable : values) {
// total
sum += intWritable.get();
}
context.write(key, new IntWritable(sum));//或 new IntWritable().set(sum)
}
}
//dirver(将dirver提出来了)
public int run(String[] args) throws Exception {
//1.get configuration
Configuration conf = new Configuration();
// conf.set(