用java写一个mapreduce的代码,对hdfs上的一个文件夹下的文件分别进行读取处理,处理完的结果写入到HDFS的output文件夹下,不同的文件生成不同的结果,在存放中按照日期进行分区
时间: 2023-04-06 11:01:06 浏览: 122
您好,以下是Java编写MapReduce代码的示例,用于对HDFS上的文件夹下的文件进行读取和处理,并将处理结果写入到HDFS的output文件夹下,不同的文件生成不同的结果,并按照日期进行分区:
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.hadoop.conf.Configuration;
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 org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
public class MapReduceExample {
public static class Map extends Mapper<LongWritable, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
String[] words = line.split(" ");
for (String w : words) {
word.set(w);
context.write(word, one);
}
}
}
public static class Reduce extends Reducer<Text, IntWritable, Text, IntWritable> {
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
context.write(key, new IntWritable(sum));
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "MapReduceExample");
job.setJarByClass(MapReduceExample.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
job.setMapperClass(Map.class);
job.setReducerClass(Reduce.class);
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String date = sdf.format(new Date());
FileInputFormat.addInputPath(job, new Path("hdfs://localhost:9000/input"));
FileOutputFormat.setOutputPath(job, new Path("hdfs://localhost:9000/output/" + date));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
以上是一个简单的MapReduce示例,用于对HDFS上的文件夹下的文件进行读取和处理,并将处理结果写入到HDFS的output文件夹下,不同的文件生成不同的结果,并按照日期进行分区。
阅读全文