| 1 | * 下面程式碼雖然看起來跑wordcount , 但其實跑helloword |
| 2 | |
| 3 | {{{ |
| 4 | #!java |
| 5 | |
| 6 | import java.io.IOException; |
| 7 | import java.util.Iterator; |
| 8 | import java.util.StringTokenizer; |
| 9 | |
| 10 | import org.apache.hadoop.conf.Configuration; |
| 11 | import org.apache.hadoop.fs.Path; |
| 12 | import org.apache.hadoop.io.IntWritable; |
| 13 | import org.apache.hadoop.io.LongWritable; |
| 14 | import org.apache.hadoop.io.Text; |
| 15 | import org.apache.hadoop.mapred.OutputCollector; |
| 16 | import org.apache.hadoop.mapred.Reporter; |
| 17 | import org.apache.hadoop.mapreduce.Job; |
| 18 | import org.apache.hadoop.mapreduce.Mapper; |
| 19 | import org.apache.hadoop.mapreduce.Reducer; |
| 20 | import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; |
| 21 | import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; |
| 22 | |
| 23 | public class wordcount { |
| 24 | static public class wcmapper extends |
| 25 | Mapper<LongWritable, Text, Text, IntWritable> { |
| 26 | private final static IntWritable one = new IntWritable(1); |
| 27 | private Text word = new Text(); |
| 28 | |
| 29 | public void map(LongWritable key, Text value, |
| 30 | OutputCollector<Text, IntWritable> output, Reporter reporter) |
| 31 | throws IOException { |
| 32 | String line = value.toString(); |
| 33 | StringTokenizer tokenizer = new StringTokenizer(line); |
| 34 | while (tokenizer.hasMoreTokens()) { |
| 35 | word.set(tokenizer.nextToken()); |
| 36 | output.collect(word, one); |
| 37 | } |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | static public class wcreducer extends |
| 42 | Reducer<Text, IntWritable, Text, IntWritable> { |
| 43 | public void reduce(Text key, Iterator<IntWritable> values, |
| 44 | OutputCollector<Text, IntWritable> output, Reporter reporter) |
| 45 | throws IOException { |
| 46 | int sum = 0; |
| 47 | while (values.hasNext()) { |
| 48 | sum += values.next().get(); |
| 49 | } |
| 50 | output.collect(key, new IntWritable(sum)); |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | public static void main(String[] args) throws Exception { |
| 55 | |
| 56 | Configuration conf = new Configuration(); |
| 57 | |
| 58 | Job job = new Job(conf, "wordcount"); |
| 59 | |
| 60 | job.setJarByClass(wordcount.class); |
| 61 | |
| 62 | FileInputFormat.setInputPaths(job, "/user/shunfa/input"); |
| 63 | FileOutputFormat.setOutputPath(job, new Path( |
| 64 | "/user/shunfa/output-wordcount11")); |
| 65 | |
| 66 | job.setMapperClass(wcmapper.class); |
| 67 | job.setReducerClass(wcreducer.class); |
| 68 | job.waitForCompletion(true); |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | }}} |
| 73 | |
| 74 | |