对于两个输入文件,即文件A和文件B,请编写MapReduce程序,对两个文件进行合并,并剔除其中重复的内容,得到一个新的输出文件C。下面是输入文件和输出文件的一个样例供参考。
输入文件A的样例如下:
20170101 x 20170102 y 20170103 x 20170104 y 20170105 z 20170106 x |
输入文件B的样例如下:
20170101 y 20170102 y 20170103 x 20170104 z 20170105 y |
根据输入文件A和B合并得到的输出文件C的样例如下:
20170101 x 20170101 y 20170102 y 20170103 x 20170104 y 20170104 z 20170105 y 20170105 z 20170106 x |
】
答:
步骤
1.启动hadoop
2.
- 在/usr/local/hadoop下建A.txt与B.txt,并输入内容
3.
- 将步骤2的文件上传hadoop上
5检查
6.
package a;
import java.io.IOException;
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;
import org.apache.hadoop.util.GenericOptionsParser;
public class Merge {
/**
* @param args
* 对A,B两个文件进行合并,并剔除其中重复的内容,得到一个新的输出文件C
*/
//重载map函数,直接将输入中的value复制到输出数据的key上
public static class Map extends Mapper<Object, Text, Text, Text>{
private static Text text = new Text();
public void map(Object key, Text value, Context context) throws IOException,InterruptedException{
text = value;
//利用MapReduce框架自带的去重和整合功能
context.write(text, new Text(""));//之间把取出来的值当做键,取一个空字符串作为value
}
}
//重载reduce函数,直接将输入中的key复制到输出数据的key上
public static class Reduce extends Reducer<Text, Text, Text, Text>{
public void reduce(Text key, Iterable<Text> values, Context context ) throws IOException,InterruptedException{
context.write(key, new Text(""));//去重功能
}
}
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
Configuration conf = new Configuration();//程序运行时参数
conf.set("fs.default.name","hdfs://localhost:9000");
String[] otherArgs = new String[]{"input/*","output"}; /* 直接设置输入参数 ,修改*/
if (otherArgs.length != 2) {
System.err.println("Usage: wordcount <in> <out>");
System.exit(2);
}
Job job = Job.getInstance(conf,"Merge and duplicate removal");//设置环境参数
job.setJarByClass(Merge.class);//设置整个程序的类名
job.setMapperClass(Map.class);//添加MyMapper类
job.setCombinerClass(Reduce.class);//连接
job.setReducerClass(Reduce.class);//添加MyReducer类
job.setOutputKeyClass(Text.class);//设置输出类型
job.setOutputValueClass(Text.class);
FileInputFormat.addInputPath(job, new Path(otherArgs[0]));//设置输入文件
FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));//设置输出文件
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
7.(不必要)
8.(不必要)
9.(终端打包,后面步骤失败--不必要)
10。直接打包,成功
10.运行
(二)编写程序实现对输入文件的排序(没做出来)
现在有多个输入文件,每个文件中的每行内容均为一个整数。要求读取所有文件中的整数,进行升序排序后,输出到一个新的文件中,输出的数据格式为每行两个整数,第一个数字为第二个整数的排序位次,第二个整数为原待排列的整数。下面是输入文件和输出文件的一个样例供参考。
输入文件1的样例如下:
33 37 12 40 |
输入文件2的样例如下:
4 16 39 5 |
输入文件3的样例如下:
1 45 25 |
根据输入文件1、2和3得到的输出文件如下:
1 1 2 4 3 5 4 12 5 16 6 25 7 33 8 37 9 39 10 40 11 45 |
答:
1.清空题目1的痕迹,因为要用到output
2.
3. 上传
再检查上传完没
4.打包
5.运行