Hadoop 统计单词字数的例子
hadoop 的核心还是 Map-Reduce过程和 hadoop分布式文件系统 第一步:定义Map过程 /** * *Description: * *@authorcharles.wang *@createdMar12,20121:41:57PM * */ publicclassMyMapextendsMapper<Object,Text,Text,IntWritable>{ privatestaticfinalIntWritableone=newIntWritable(1); privateTextword; publicvoidmap(Objectkey,Textvalue,Contextcontext) throwsIOException,InterruptedException{ Stringline=value.toString(); StringTokenizertokenizer=newStringTokenizer(line); while(tokenizer.hasMoreTokens()){ word=newText(); word.set(tokenizer.nextToken()); context.write(word,one); } } } 第二步: 定义 Reduce 过程 /** * *Description: * *@authorcharles.wang *@createdMar12,20121:48:18PM * */ publicclassMyReduceextendsReducer<Text,IntWritable,Text,IntWritable>{ publicvoidreduce(Textkey,Iterable<IntWritable>values,Contextcontext) throwsIOException,InterruptedException{ intsum=0; for(IntWritableval:values){ sum+=val.get(); } context.write(key,newIntWritable(sum)); } } 编写一个Driver 来执行Map-Reduce过程 publicclassMyDriver{ publicstaticvoidmain(String[]args)throwsException{ Configurationconf=newConfiguration(); conf.set("hadoop.job.ugi","root,root123"); Jobjob=newJob(conf,"Hello,hadoop!^_^"); job.setJarByClass(MyDriver.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(IntWritable.class); job.setMapperClass(MyMap.class); job.setCombinerClass(MyReduce.class); job.setReducerClass(MyReduce.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); FileInputFormat.setInputPaths(job,newPath(args[0])); FileOutputFormat.setOutputPath(job,newPath(args[1])); job.waitForCompletion(true); } } 本文转自 charles_wang888 51CTO博客,原文链接:http://blog.51cto.com/supercharles888/840723,如需转载请自行联系原作者