import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
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;
import java.io.IOException;
public class Wordcount111 {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
// conf.set("fs.defaultFS","hdfs:potter2:9000");
// System.setProperty("HADOOP_USER_NAME","potter");
FileSystem fs = FileSystem.get(conf);
Job job = Job.getInstance();
job.setJarByClass(Wordcount111.class);
job.setMapperClass(WordcountMapper.class);
job.setReducerClass(WordcountReaducer.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(IntWritable.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
Path input = new Path("D:\\111\\222\\hello.txt");
Path output = new Path("D:\\aaa");
FileInputFormat.setInputPaths(job,input);
FileOutputFormat.setOutputPath(job,output);
if (fs.exists(output)){
fs.delete(output,true);
}
boolean isdone = job.waitForCompletion(true);
System.exit(isdone ? 0 :1);
}
public static class WordcountMapper extends Mapper<LongWritable,Text,Text,IntWritable>{
Text text = new Text();
IntWritable ii = new IntWritable();
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String[] split = value.toString().split(",");
for (String word : split){
text.set(word);
ii.set(1);
context.write(text,ii);
}
}
}
public static class WordcountReaducer extends Reducer<Text,IntWritable,Text,IntWritable>{
IntWritable ii = new IntWritable();
@Override
protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int count = 0;
for (IntWritable value : values){
count += value.get();
}
ii.set(count);
context.write(key,ii);
}
}
}
运行结果:
i 1
jump 2
you 1