实现过程所需的java代码
1,在hdfs目录/tmp/input/wordcount中有一系列文件,内容均为","号分隔,
求按","号分隔的各个元素的出现频率,输出到目录/tmp/个人用户名的hdfs目录中。
实现代码:
package com.tledu.hadoop.mr.homework;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
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;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class HomeWork1 {
public static class HomeWork1Mapper extends Mapper<Object, Text, Text, IntWritable> {
Text word = new Text();
IntWritable one = new IntWritable(1);
@Override
protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
StringTokenizer str = new StringTokenizer(value.toString(), ",");
while (str.hasMoreTokens()) {
word.set(str.nextToken());
context.write(word, one);
}
}
}
public static class HomeWork1Reducer extends Reducer<Text, IntWritable, Text, IntWritable> {
IntWritable sumRes = new IntWritable();
@Override
protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
sumRes.set(sum);
context.write(key, sumRes);
}
}
public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
// 1. 创建配置
Configuration conf = new Configuration();
// 2. 创建任务
Job job = Job.getInstance(conf, "homework1");
// 3. 设置对应类
job.setJarByClass(HomeWork1.class);
job.setMapperClass(HomeWork1Mapper.class);
job.setCombinerClass(HomeWork1Reducer.class);
job.setReducerClass(HomeWork1Reducer.class);
// 4. 输出的kv类型
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
// 5. 输入和输出的路径
// 获取所有输入的txt文件
List<String> fileList = getTxtFileListFromPath(args[0]);
for (String filePath : fileList) {
FileInputFormat.addIn