Hadoop 2.2.0新API的WordCount例子(运行通过)

import java.util.StringTokenizer;


import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
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 NewVersionWordCount {

public static class MapClass extends Mapper<LongWritable, Text, Text, IntWritable>{

private final static IntWritable one=new IntWritable(1);
private Text word=new Text();

protected void setup(Context context){
System.out.println("mapper setup:"+context.getJobName());
}

public void map(LongWritable key,Text value,Context context){//map函数
String line=value.toString();
StringTokenizer tokenizer=new StringTokenizer(line);
try{
while(tokenizer.hasMoreTokens()){
word.set(tokenizer.nextToken());
context.write(word, one);
}}catch (Exception e) {
e.printStackTrace();
}

}

       protected void cleanup(Context context){
      System.out.println("mapper cleanup:"+context.getUser());
}
}


public static class ReduceClass extends Reducer<Text, IntWritable, Text, IntWritable>{

protected void setup(Context context){
System.out.println("reduce setup:"+context.getUser());
}

public void reduce(Text key,Iterable<IntWritable> values,Context context){//reduce函数
int sum=0;
for(IntWritable value:values){
sum+=value.get();
}
try{
context.write(key, new IntWritable(sum));
}catch (Exception e) {
e.printStackTrace();
}

}

protected void cleanup(Context context){
System.out.println("reduce cleanup:"+context.getUser());
}

}

public static void main(String[] args)throws Exception {

String inputPath="/user/User/input";
String outPath="/user/User/output";

Configuration conf=new Configuration();
Job job=new Job(conf);
job.setJobName("wordCount");
job.setJarByClass(NewVersionWordCount.class);
job.setMapperClass(MapClass.class);
job.setReducerClass(ReduceClass.class);

job.setInputFormatClass(org.apache.hadoop.mapreduce.lib.input.TextInputFormat.class);

job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);

/*FileSystem fileSystem=FileSystem.get(conf);
if(fileSystem.exists(new Path(outPath))){
fileSystem.delete(new Path(outPath),true);
}*/

FileInputFormat.addInputPath(job,new Path(inputPath));
FileOutputFormat.setOutputPath(job, new Path(outPath));

boolean complete=job.waitForCompletion(true);
if(!complete){
throw new RuntimeException();
}

}


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值