利用eclipse 新建hadoop的WordCount项目

云计算 waitig 447℃ 百度已收录 0评论

一:打开elipse  点击【File】—>【Project】,选择【Map/Reduce Project】,输入项目名称WordCount,一直回车

二:在项目中新建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<Object,Text,Text,IntWritable>{

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<Text,IntWritable,Text,IntWritable> {

private IntWritable result = new IntWritable();

public void reduce(Text key, Iterable<IntWritable> 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();

@SuppressWarnings("deprecation")
Job job = new Job(conf, "wordcount");

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);

}
}



三:在HDFS上创建目录文件输入目录:/data/input

hadoop fs -mkdir /data/input

四:上传文件到文件输入目录中

hadoop fs -copyFromLocal 上传文件路径 /data/input

五;点击WordCount.java,右键,点击【Run As】—>【Run Configurations】,配置运行参数,即输入和输出文件夹


六;点击运行后在上面出现output1文件夹表示成功(output目录不能重复)点击打开即可看到结果

导包问题:如果报类无法找到等错误就把hadoop安装目录share目录下的common,HDFS,yarn下的包都加到项目中,还有mapreduce下的包以及mapreduce/lib下的包都导入项目


本文由【waitig】发表在等英博客
本文固定链接:利用eclipse 新建hadoop的WordCount项目
欢迎关注本站官方公众号,每日都有干货分享!
等英博客官方公众号
点赞 (0)分享 (0)