1,寫程序MyWordCount.java
hduser@ubuntu:/usr/local/hadoop$ gedit MyWordCount.java
package org.myorg;
import java.io.IOException;
import java.util.*;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.util.*;
public class WordCount {
public static void main(String[] args) throws Exception {
JobConf conf = new JobConf(WordCount.class);
conf.setJobName("wordcount");
//conf.setNumReduceTasks(0);
conf.setOutputKeyClass(Text.class);
conf.setOutputValueClass(IntWritable.class);
conf.setMapperClass(Map.class);
conf.setCombinerClass(Reduce.class);
//conf.setReducerClass(Reduce.class);
conf.setInputFormat(TextInputFormat.class);
conf.setOutputFormat(TextOutputFormat.class);
FileInputFormat.setInputPaths(conf, new Path(args[0]));
FileOutputFormat.setOutputPath(conf, new Path(args[1]));
JobClient.runJob(conf);
}
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();
public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
String line = value.toString();
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
word.set(tokenizer.nextToken());
output.collect(word, one);
}
}
}
public static class Reduce extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> {
public void reduce(Text key, Iterator<IntWritable> values, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
int sum = 0;
while (values.hasNext()) {
sum += values.next().get();
}
output.collect(key, new IntWritable(sum));
}
}
}
源文檔 <http://hadoop.apache.org/docs/r0.18.3/mapred_tutorial.html>
注:conf.setInputFormat(TextInputFormat.class); //TextInputFormat是默認的InputFormat。這說明Map類的鍵是LongWritable類型,存儲整個文件的字節偏移量,值是Text類型,是一行內容。StringTokenizer 把行按空格拆分成單詞。
conf.setOutputFormat(TextOutputFormat.class); //輸出格式爲TextOutputFormat,把輸出記錄寫成文本行。鍵值可以使任何類型,因爲可以用toString()方法轉成字符串。這裏的輸出鍵是Text類型,值是IntWritable類型。
2,編譯
Mkdir wordcountsource
hduser@ubuntu:/usr/local/hadoop$ javac -classpath hadoop-core-1.1.1.jar -d wordcountsource MyWordCount.java
編譯java到wordcountsource文件夾下
如果出現錯誤:error while writing Map: could not create parent directories
說明沒有寫入input文件的權限
3,生成jar
hduser@ubuntu:/usr/local/hadoop$ sudo jar -cvf MyWordCount.jar -C wordcountsource/ .
在當前目錄下生成MyWordCount.jar
Ant打包
4,在input文件夾下創建file0和file1
hduser@ubuntu:/usr/local/hadoop/input$ mkdir input //input文件夾爲輸入
hduser@ubuntu:/usr/local/hadoop/input$ sudo gedit file0
hduser@ubuntu:/usr/local/hadoop/input$ sudo gedit file1
5,運行MyWordCount.jar
hduser@ubuntu:/usr/local/hadoop$ sudo bin/hadoop jar MyWordCount.jar org.myorg.MyWordCount input output
確保有創建output的權限
6,查看結果
hduser@ubuntu:/usr/local/hadoop$ cat output/part-00000
Bye 1
Hello 1
World 2