一、自定义InputFormat

  InputFormat是输入流,在前面的例子中使用的是文件输入输出流FileInputFormat和FileOutputFormat,而FileInputFormat和FileOutputFormat它们默认使用的是继承它们的子类TextInputFormat和TextOutputFormat,以Text的方式去读取数据。

  当我们遇到许多小文件,要将他们整理合成为一个文件SequenceFile(存储了多个小文件),且文件内的存储格式为:文件路径+文件内容,这时我们可以通过封装自定义的InputFormat输入流来实现需求。

  思路如下:

    1.自定义FuncFileInputFormat类继承FileInputFormat(参数类型为NullWritable和BytesWritable),并重写isSplitable和createRecordReader方法;

    2.isSplitable方法中return false即可表示不切割,createRecordReader方法中要返回一个RecordReader类,这是我们要自定义的对输入文件的业务逻辑,所以创建FuncRecordReader类;

    3.FuncRecordReader类继承RecordReader类,参数类型同为NullWritable和BytesWritable,重写initialize、nextKeyValue、getCurrentKey、getCurrentValue、getProcess、close方法;

    4.Mapper:初始化setup方法,通过context拿到切片、获取路径、将路径写入定义的全局变量Text t,然后在map阶段将t和value输出到reducer;

    5.Reducer:遍历values,输出key,value;

    6.Driver:在设置完Mapper和Reducer类后,添加设置setInputFormatClass为FuncFileInputFormat、设置setOutputFormatClass为SequenceFileOutputFormat。

  代码如下:

/**
* @author: PrincessHug
* @date: 2019/3/29, 20:49
* @Blog: https://www.cnblogs.com/HelloBigTable/
*/
public class FuncFileInputFormat extends FileInputFormat<NullWritable, BytesWritable> {
@Override
protected boolean isSplitable(JobContext context, Path filename) {
return false;
} @Override
public RecordReader<NullWritable, BytesWritable> createRecordReader(InputSplit inputSplit, TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException {
FuncRecordReader recordReader = new FuncRecordReader();
return recordReader;
}
} public class FuncRecordReader extends RecordReader<NullWritable, BytesWritable> {
boolean isProcess = false;
FileSplit split;
Configuration conf;
BytesWritable value = new BytesWritable(); //初始化
@Override
public void initialize(InputSplit inputSplit, TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException {
//初始化切片文件
this.split = (FileSplit) inputSplit; //初始化配置信息
conf = taskAttemptContext.getConfiguration(); } //获取下一个文件
@Override
public boolean nextKeyValue() throws IOException, InterruptedException {
if (!isProcess){
//根据切片的长度来创建缓冲区
byte[] buf = new byte[(int) split.getLength()];
FSDataInputStream fis = null;
FileSystem fs = null; try {
//获取路径
Path path = split.getPath();
//根据路径获取文件系统
fs = path.getFileSystem(conf);
//拿到输入流
fis = fs.open(path);
//数据拷贝
IOUtils.readFully(fis,buf,0,buf.length);
//拷贝缓存到最终的输出
value.set(buf,0,buf.length);
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeStream(fis);
IOUtils.closeStream(fs);
}
isProcess = true;
return true;
} return false;
} @Override
public NullWritable getCurrentKey() throws IOException, InterruptedException {
return NullWritable.get();
} @Override
public BytesWritable getCurrentValue() throws IOException, InterruptedException {
return value;
} @Override
public float getProgress() throws IOException, InterruptedException {
return 0;
} @Override
public void close() throws IOException { }
} public class SequencceFileMapper extends Mapper<NullWritable, BytesWritable, Text,BytesWritable> {
Text t = new Text(); @Override
protected void setup(Context context) throws IOException, InterruptedException {
//拿到切片信息
FileSplit split = (FileSplit) context.getInputSplit();
//路径
Path path = split.getPath();
//即带路径有待名称
t.set(path.toString());
} @Override
protected void map(NullWritable key, BytesWritable value, Context context) throws IOException, InterruptedException {
context.write(t,value);
}
} public class SequenceFileReducer extends Reducer<Text, BytesWritable,Text,BytesWritable> {
@Override
protected void reduce(Text key, Iterable<BytesWritable> values, Context context) throws IOException, InterruptedException {
for (BytesWritable v:values){
context.write(key,v);
}
}
} public class SequenceFileDriver {
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
//1.获取job信息
Configuration conf = new Configuration();
Job job = Job.getInstance(conf);
//2.获取Jar包
job.setJarByClass(SequenceFileDriver.class); //3.获取Mapper、Redcuer类
job.setMapperClass(SequencceFileMapper.class);
job.setReducerClass(SequenceFileReducer.class); //4.设置自定义读取方法
job.setInputFormatClass(FuncFileInputFormat.class); //5.设置默认的输出方式
job.setOutputFormatClass(SequenceFileOutputFormat.class); //6.获取Mapper输出数据类型
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(BytesWritable.class); //7.获取Reducer输出数据类型
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(BytesWritable.class); //8.设置输入存在的路径与处理后的结果路径
FileInputFormat.setInputPaths(job,new Path("G:\\mapreduce\\inputformat\\in"));
FileOutputFormat.setOutputPath(job,new Path("G:\\mapreduce\\inputformat\\out")); //9.提交任务
if (job.waitForCompletion(true)){
System.out.println("运行完成!");
}else {
System.out.println("运行失败!");
}
}
}

  

二、自定义OutputFormat

  需求:目前我们有一个网站ip的文件,每行都有一个网站的ip地址,要求我们将含有“www.baidu.com”的ip地址取出放入一个结果文件,其他的地址放入另一个结果文件。

  思路:1.首先Mapper、Reduer就是简单的读取数据、写出数据;

    2.自定义FuncFileOutputFormat,重写它的getRecordWriter方法,返回一个FIleRecordWriter对象,这里我们再定义一个FileRecordWriter,重写FileRecordWriter、write、close方法;

    3.Driver:再设置Reducer输出后添加设置setOutputFormatClass为我们自定义的FuncFileOutputFormat即可;

  代码如下:

/**
* @author: PrincessHug
* @date: 2019/3/30, 14:44
* @Blog: https://www.cnblogs.com/HelloBigTable/
*/
public class FileMapper extends Mapper<LongWritable, Text, IntWritable, Text> {
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
context.write(new IntWritable(1),new value);
}
} public class FileReducer extends Reducer<IntWritable, Text,Text,NullWritable> {
@Override
protected void reduce(IntWritable key, Iterable<Text> values, Context context) throws IOException, InterruptedException { for (Text k:values){
String s = k.toString() + "\n";
context.write(new Text(s),NullWritable.get());
} }
} public class FuncFileOutputFormat extends FileOutputFormat<Text, NullWritable> {
@Override
public RecordWriter<Text, NullWritable> getRecordWriter(TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException {
return new FileRecordWriter(taskAttemptContext);
}
} public class FileRecordWriter extends RecordWriter<Text, NullWritable> {
Configuration conf = null;
FSDataOutputStream baidulog = null;
FSDataOutputStream otherlog = null; //定义数据输出路径
public FileRecordWriter(TaskAttemptContext taskAttemptContext) throws IOException {
//获取配置信息和文件系统
conf = taskAttemptContext.getConfiguration();
FileSystem fs = FileSystem.get(conf);
//定义输出路径
itstarlog = fs.create(new Path("G:\\mapreduce\\outputformat\\out\\itstart\\baidu.logs"));
otherlog = fs.create(new Path("G:\\mapreduce\\outputformat\\out\\other\\other.logs"));
} //数据输出
@Override
public void write(Text key, NullWritable value) throws IOException, InterruptedException {
if (key.toString().contains("baidu")){
baidulog.write(key.getBytes());
}else {
otherlog.write(key.getBytes());
}
} //关闭资源
@Override
public void close(TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException {
if (itstarlog != null){
itstarlog.close();
}
if (otherlog != null){
otherlog.close();
}
}
} public class FileDriver {
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
//配置、job
Configuration conf = new Configuration();
Job job = Job.getInstance(conf); //jar包
job.setJarByClass(FileDriver.class); //Mapper、Reducer
job.setMapperClass(FileMapper.class);
job.setReducerClass(FileReducer.class); //Mapper输出
job.setMapOutputKeyClass(IntWritable.class);
job.setMapOutputValueClass(Text.class); //Reudcer输出
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(NullWritable.class); //自定义输出类
job.setOutputFormatClass(FuncFileOutputFormat.class); //文件输入输出流
FileInputFormat.setInputPaths(job,new Path("G:\\mapreduce\\outputformat\\in"));
FileOutputFormat.setOutputPath(job,new Path("G:\\mapreduce\\outputformat\\out")); //提交任务
if (job.waitForCompletion(true)){
System.out.println("运行完成!");
}else {
System.out.println("运行失败!");
}
}
}

  

自定义InputFormat和OutputFormat案例的更多相关文章

  1. 【Hadoop离线基础总结】MapReduce自定义InputFormat和OutputFormat案例

    MapReduce自定义InputFormat和OutputFormat案例 自定义InputFormat 合并小文件 需求 无论hdfs还是mapreduce,存放小文件会占用元数据信息,白白浪费内 ...

  2. MapReduce自定义InputFormat和OutputFormat

    一.自定义InputFormat 需求:将多个小文件合并为SequenceFile(存储了多个小文件) 存储格式:文件路径+文件的内容 c:/a.txt I love Beijing c:/b.txt ...

  3. 自定义inputformat和outputformat

    1. 自定义inputFormat 1.1 需求 无论hdfs还是mapreduce,对于小文件都有损效率,实践中,又难免面临处理大量小文件的场景,此时,就需要有相应解决方案 1.2 分析 小文件的优 ...

  4. 【转自】自定义InputFormat、OutputFormat

    转自:http://www.cnblogs.com/xiaolong1032/p/4529534.html 一:自定义实现InputFormat *数据源来自于内存*1.InputFormat是用于处 ...

  5. Hadoop案例(六)小文件处理(自定义InputFormat)

    小文件处理(自定义InputFormat) 1.需求分析 无论hdfs还是mapreduce,对于小文件都有损效率,实践中,又难免面临处理大量小文件的场景,此时,就需要有相应解决方案.将多个小文件合并 ...

  6. Hadoop中常用的InputFormat、OutputFormat(转)

    Hadoop中的Map Reduce框架依赖InputFormat提供数据,依赖OutputFormat输出数据,每一个Map Reduce程序都离不开它们.Hadoop提供了一系列InputForm ...

  7. MapReduce自定义InputFormat,RecordReader

    MapReduce默认的InputFormat是TextInputFormat,且key是偏移量,value是文本,自定义InputFormat需要实现FileInputFormat,并重写creat ...

  8. 自定义InputFormat

    回顾: 在上一篇https://www.cnblogs.com/superlsj/p/11857691.html详细介绍了InputFormat的原理和常见的实现类.总结来说,一个InputForma ...

  9. Java基础知识强化之集合框架笔记08:Collection集合自定义对象并遍历案例(使用迭代器)

    1. Collection集合自定义对象并遍历案例(使用迭代器) (1)首先定义一个Student.java,如下: package com.himi.collectionIterator; publ ...

随机推荐

  1. zabbix误报交换机重启

    交换机的sysUpTime是由一个32-bit的counter来计数的,单位是0.01秒,所以最大时间为496天,过了496天就溢出,变成0,然后又重新计算时间,所以zabbix误报. snmpwal ...

  2. Zabbix通过JMX方式监控java中间件

    Zabbix2.0添加了支持用于监控JMX应用程序的服务进程,称为“Zabbix-Java-gateway”:它是用java写的一个程序. 工作原理: zabbix_server想知道一台主机上的特定 ...

  3. 1: jsp的4个作用域 pageScope、requestScope、sessionScope、applicationScope的区别

    1.区别: 1.page指当前页面有效.在一个jsp页面里有效 2.request 指在一次请求的全过程中有效,即从http请求到服务器处理结束,返回响应的整个过程,存放在HttpServletReq ...

  4. 将服务器文件上传到ftp shell操作

    date cd /home/data today_now=`date +%Y%m%d` #当前日期 cur_date=${today_now::} #echo ${cur_date} #判断是否文件生 ...

  5. Java入门:基础算法之二进制转换为十进制

    Java有两种方法可以将二进制数转换为十进制数: 1)使用Integer类的Integer.parseInt()方法. 2)自己编写转换逻辑. 方法1:使用Integer.parseInt()实现二进 ...

  6. JavaEESSM框架配置文件

    SSM框架理解 最近两星期一直在学JavaEE的MVC框架,因为之前学校开的JavaEE课程就一直学的吊儿郎当的,所以现在真正需要掌握就非常手忙脚乱,在此记录下这段时间学习的感悟,如有错误,希望大牛毫 ...

  7. TPS、并发用户数、吞吐量关系

    TPS.并发用户数.吞吐量关系 摘要 主要描述了在性能测试中,关于TPS.并发用户数.吞吐量之间的关系和一些计算方法. loadrunner TPS 目录[-] 一.系统吞度量要素: 二.系统吞吐量评 ...

  8. [再寄小读者之数学篇](2014-06-22 求导数 [中国科学技术大学2014年高等数学B考研试题])

    设 $f(x)=x^2\ln(x+1)$, 求 $f^{(n)}(0)$. 解答: 利用 Leibniz 公式易知 $f'(0)=f''(0)=0$, $f^{(n)}(0)=(-1)^{n-3} n ...

  9. [物理学与PDEs]第1章第9节 Darwin 模型 9.2 Maxwell 方程组的一个定解问题

    设 $\Omega$ 为一有界区域, 外部为理想导体 $(\sigma=+\infty)$, 则 $\Omega$ 中电磁场满足 Maxwell 方程组 $$\beex \bea \ve\cfrac{ ...

  10. Java(6)for循环

    一.for循环的使用场合 1.1.while循环——先判断,再循环 while(1.条件表达式){      //2.循环操作      //3.更改循环条件表达式 } 1.2.do…while——先 ...