1.建立一个maven工程
2.编写pom文件
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.luo
hadoop
1.0-SNAPSHOT
apache
http://maven.apache.org
org.apache.hadoop
hadoop-core
1.2.1
org.apache.hadoop
hadoop-common
2.7.2
然后导入改变可以使用idea工具,也可以使用命令行;
mvn clean compile需要cd 到项目地址
可以参考文章 http://www.jianshu.com/p/9b9cfc486a28
编写WordCount.java
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
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 WordCount {
public static class TokenizerMapper
extends Mapper {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(Object key, Text value, Context context
) throws IOException, InterruptedException {
StringTokenizer itr = new StringTokenizer(value.toString());
while (itr.hasMoreTokens()) {
word.set(itr.nextToken());
context.write(word, one);
}
}
}
public static class IntSumReducer
extends Reducer {
private IntWritable result = new IntWritable();
public void reduce(Text key, Iterable values,
Context context
) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
result.set(sum);
context.write(key, result);
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "word count");
job.setJarByClass(WordCount.class);
job.setMapperClass(TokenizerMapper.class);
job.setCombinerClass(IntSumReducer.class);
job.setReducerClass(IntSumReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
4.在项目目录下建立 input 文件夹
屏幕快照 2017-09-23 下午10.54.45.png
5.点击File->Project Structure,在弹出来的对话框中选择Modules项,点击Sources选项卡,将Language level调整为7。(如果你用到版本控制的话,可以在这里将input文件夹标记为Excluded).
屏幕快照 2017-09-23 下午10.56.23.png
6.配置运行参数
这里我们需要配置此程序运行时的Main class,以及WordCount需要的输入输出路径。
在Intellij菜单栏中选择Run->Edit Configurations,在弹出来的对话框中点击+,新建一个Application配置。配置Main class为WordCount(可以点击右边的…选择),Program arguments为input/ output/,即输入路径为刚才创建的input文件夹,输出为output。
屏幕快照 2017-09-23 下午10.57.47.png
Result
可以点击运行了,可以debug。
如果需要重新运行需要把output文件夹删除!