第一个hadoop 程序
首先检查hadoop是否安装并配置正确
然后建立WordCount.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 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));
}
}
public static void main(String[] args) throws Exception {
JobConf conf = new JobConf(WordCount.class);
conf.setJobName("wordcount");
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);
}
}
然后编译WordCount.java文件,把它制作成可执行jar包
javac -d . -classpath /root/hadoop-0.20.1/hadoop-0.20.1-core.jar WordCount.java
然后在org的同级目录上建立manifest.mf
在里面写上Main-Class: org.myorg.WordCount
然后保存并执行jar -cvfm count.jar manifest.mf org/
然后在hdfs上建立一个文件夹,hadoop fs -mkdir /test
hadoop fs -put /root/wordtestnum.txt /test
然后执行hadoop jar /root/Desktop/count.jar /test/in /test/out
查看运行结果hadoop fs -cat /test/out/part-00000
作者:虾米哥
微信公众号:IT虾米,左侧为二维码
个人技术网站-IT虾米网:http://www.itxm.cn
个人技术网站-编程符号网:http://www.itfh.cn
个人技术网站-IT源码网:http://www.itym.cn
新浪微博:https://weibo.com/u/2814576687
如果你想及时得到个人撰写文章以及著作的消息推送,或者想看看个人推荐的技术资料,可以扫描左边二维码(或者长按识别二维码)关注个人公众号。
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。