解决Hadoop命令方式运行WordCount异常Class WordCount$XXXMapper not found

WordCount.java 注意把job.setJarByClass(WordCount.class);改成job.setJar("wc.jar");,解决类找不到的问题

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.setJar("wc.jar");
    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);
  }
}

使用hadoop命令进行编译和执行

[hadoop@nn01 ~]$ mkdir demo
[hadoop@nn01 ~]$ cd demo
[hadoop@nn01 demo]$ mkdir input
[hadoop@nn01 demo]$ cd input/
[hadoop@nn01 input]$ echo "hello hadoop hello world" > 1.txt
[hadoop@nn01 input]$ echo "hello zheng from hadoop" > 2.txt
[hadoop@nn01 ~]$ hadoop fs -put ./demo /
[hadoop@nn01 hadoop-2.9.0]$ bin/hadoop com.sun.tools.javac.Main WordCount.java
[hadoop@nn01 hadoop-2.9.0]$ jar cf wc.jar WordCount*.class
[hadoop@nn01 hadoop-2.9.0]$ bin/hadoop jar wc.jar WordCount /demo/input /demo/output
执行结果

解决Hadoop命令方式运行WordCount异常Class WordCount$XXXMapper not found_第1张图片

你可能感兴趣的:(Hadoop)