本程序实现最简单的MapReduce程序:计算文章的词频统计,wordcount
头文件
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.mapred.*;
import java.io.IOException;
import java.util.Iterator;
import java.util.StringTokenizer;
其他部分
public class WordCount {
public static class Map extends MapReduceBase implements Mapper<LongWritable, Text, Text, IntWritable>{
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
@Override
public void map(LongWritable longWritable, Text text, OutputCollector<Text, IntWritable> outputCollector, Reporter reporter) throws IOException {
String line = text.toString();
StringTokenizer tokenizer = new StringTokenizer(line);
while(tokenizer.hasMoreTokens()){
word.set(tokenizer.nextToken());
outputCollector.collect(word,one);
}
}
}
public static class Reduce extends MapReduceBase implements Reducer<Text,IntWritable,Text, IntWritable>{
@Override
public void reduce(Text text, Iterator<IntWritable> iterator, OutputCollector<Text, IntWritable> outputCollector, Reporter reporter) throws IOException {
int sum= 0;
while(iterator.hasNext()){
sum += iterator.next().get();
}
outputCollector.collect(text, new IntWritable(sum));
}
}
public static void main(String[] args) throws Exception{
//Configuration conf = new Configuration();
//Configuration conf=new Configuration();
JobConf conf = new JobConf(WordCount.class);
conf.set("fs.defaultFS", "hdfs://localhost:9000");
conf.set("fs.hdfs.omp", "org.apache.hadoop.hdfs.DistributedFileSystem");
conf.setJobName("wordCount");
conf.setOutputKeyClass(Text.class);
conf.setOutputValueClass(IntWritable.class);
conf.setMapperClass(Map.class);
conf.setReducerClass(Reduce.class);
conf.setInputFormat(TextInputFormat.class);
conf.setOutputFormat(TextOutputFormat.class);
FileInputFormat.setInputPaths(conf,new Path("/input/book.txt"));
FileOutputFormat.setOutputPath(conf, new Path("/output"));
JobClient.runJob(conf);
}
}
网友评论