import java.io.DataOutput;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map; import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.Reducer.Context;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.CombineFileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.CombineFileRecordReader;
import org.apache.hadoop.mapreduce.lib.input.CombineFileSplit;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.input.LineRecordReader;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileRecordReader;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner; public class TestCombine extends Configured implements Tool {
private static class ProvinceMapper extends
Mapper<Object, Text, Text, Text> {
@Override
protected void map(Object key, Text value, Context context)
throws IOException, InterruptedException {
System.out.println("value : " + value + " Context " + context);
context.write(value, value);
}
} private static class ProvinceReducer extends
Reducer<Text, Text, Text, Text> {
@Override
protected void reduce(Text key, Iterable<Text> values, Context context)
throws IOException, InterruptedException {
for (Text va : values) {
System.out.println("reduce " + key);
context.write(key, key);
}
}
} // 输入格式
static class CombineSequenceFileInputFormat<K, V> extends CombineFileInputFormat<K, V> {
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public RecordReader<K, V> createRecordReader(InputSplit split, TaskAttemptContext context) throws IOException {
return new CombineFileRecordReader((CombineFileSplit)split, context, CombineLineRecordReader.class);
}
} static class CombineLineRecordReader<K, V> extends RecordReader<K, V> {
private CombineFileSplit split;
private TaskAttemptContext context;
private int index;
private RecordReader<K, V> rr; @SuppressWarnings("unchecked")
public CombineLineRecordReader(CombineFileSplit split, TaskAttemptContext context, Integer index) throws IOException, InterruptedException {
this.index = index;
this.split = (CombineFileSplit) split;
this.context = context; this.rr = (RecordReader<K, V>) ReflectionUtils.newInstance(LineRecordReader.class, context.getConfiguration());
} @SuppressWarnings("unchecked")
@Override
public void initialize(InputSplit curSplit, TaskAttemptContext curContext) throws IOException, InterruptedException {
this.split = (CombineFileSplit) curSplit;
this.context = curContext; if (null == rr) {
rr = ReflectionUtils.newInstance(SequenceFileRecordReader.class, context.getConfiguration());
} FileSplit fileSplit = new FileSplit(this.split.getPath(index),
this.split.getOffset(index), this.split.getLength(index),
this.split.getLocations()); this.rr.initialize(fileSplit, this.context);
} @Override
public float getProgress() throws IOException, InterruptedException {
return rr.getProgress();
} @Override
public void close() throws IOException {
if (null != rr) {
rr.close();
rr = null;
}
} @Override
public K getCurrentKey()
throws IOException, InterruptedException {
return rr.getCurrentKey();
} @Override
public V getCurrentValue()
throws IOException, InterruptedException {
return rr.getCurrentValue();
} @Override
public boolean nextKeyValue() throws IOException, InterruptedException {
return rr.nextKeyValue();
}
} // 输出格式
static class MyOutputFormat extends FileOutputFormat<Text, Text>{
@Override
public RecordWriter<Text, Text> getRecordWriter(
TaskAttemptContext job) throws IOException, InterruptedException {
return new MyRecordWriter(job);
}
} public static class MyRecordWriter extends RecordWriter<Text, Text> {
private Map<String, FSDataOutputStream> outputMap = null;
private static final String LINESEPARATOR = "\n";
private FileSystem fs;
private JobContext job; public MyRecordWriter(JobContext job) throws IOException {
this.outputMap = new HashMap<String, FSDataOutputStream>();
this.job = job;
this.fs = FileSystem.get(job.getConfiguration());
} // 参考 MultipleOutputs
public void write(Text key, Text value) throws IOException {
String k = key.toString();
if(k.isEmpty())
return;
FSDataOutputStream out = outputMap.get(k);
if(out==null) {
if(k.isEmpty())
System.out.println(value.toString());
Path outputPath = new Path(FileOutputFormat.getOutputPath(job), k);
if(!fs.exists(outputPath))
out = fs.create(outputPath);
else
return;
outputMap.put(k, out);
}
out.write(value.getBytes());
out.write(LINESEPARATOR.getBytes());
} @Override
public void close(TaskAttemptContext context) throws IOException,
InterruptedException {
for(FSDataOutputStream out : outputMap.values()) {
out.close();
}
}
} public int run(String[] args) throws Exception {
Configuration conf = new Configuration(); Job job = new Job(conf);
job.setJobName("TestCombine");
job.setJarByClass(TestCombine.class); job.setMapperClass(ProvinceMapper.class);
job.setReducerClass(ProvinceReducer.class); //job.setInputFormatClass(CombineSequenceFileInputFormat.class);
job.setOutputFormatClass(MyOutputFormat.class); job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class); String inpath = "/home/hadoop/tmp/combine";
String outpath = "/home/hadoop/tmp/combineout";
Path p = new Path(outpath); FileSystem fs = FileSystem.get(conf);
if (fs.exists(p)){
fs.delete(p);
}
FileInputFormat.addInputPaths(job, inpath);
FileOutputFormat.setOutputPath(job, p); return job.waitForCompletion(true) ? 0 : 1;
} public static void main(String[] args) throws Exception {
int ret = ToolRunner.run(new TestCombine(), args);
System.exit(ret);
}
}

MR中简单实现自定义的输入输出格式的更多相关文章

  1. Hadoop(七):自定义输入输出格式

    MR输入格式概述 数据输入格式 InputFormat. 用于描述MR作业的数据输入规范. 输入格式在MR框架中的作用: 文件进行分块(split),1个块就是1个Mapper任务. 从输入分块中将数 ...

  2. [ACM训练] ACM中巧用文件的输入输出来改写acm程序的输入输出 + ACM中八大输入输出格式

    ACM中巧用文件的输入输出来改写acm程序的输入输出 经常有见大神们使用文件来代替ACM程序中的IO,尤其是当程序IO比较复杂时,可以使自己能够更专注于代码的测试,而不是怎样敲输入. C/C++代码中 ...

  3. 教你一招:在PowerPoint中自定义可输入文本的占位符

    日常生活中,当我们设计多媒体课件时,默认的版式其实已经够用了.但是,很多时候,我们需要更加个性一点,所以,我们需要自定义很多东西.本文介绍在PowerPoint中自定义可输入文本的占位符. 一.占位符 ...

  4. 在浏览器中简单输入一个网址,解密其后发生的一切(http请求的详细过程)

    在浏览器中简单输入一个网址,解密其后发生的一切(http请求的详细过程) 原文链接:http://www.360doc.com/content/14/1117/10/16948208_42571794 ...

  5. Settings > Editor > Live Templates 中自定义快速输入

    Settings > Editor > Live Templates 中自定义快速输入

  6. Hadoop MapReduce编程 API入门系列之自定义多种输入格式数据类型和排序多种输出格式(十一)

    推荐 MapReduce分析明星微博数据 http://git.oschina.net/ljc520313/codeexample/tree/master/bigdata/hadoop/mapredu ...

  7. MapReduce的输入输出格式

    默认的mapper是IdentityMapper,默认的reducer是IdentityReducer,它们将输入的键和值原封不动地写到输出中. 默认的partitioner是HashPartitin ...

  8. C语言第一次作业——输入输出格式

    题目1温度转换 本题要求编写程序,计算华氏温度150°F对应的摄氏温度.计算公式:C=5×(F−32)/9,式中:C表示摄氏温度,F表示华氏温度,输出数据要求为整型. 1.实验代码 #include& ...

  9. CString中Format函数与格式输入与输出

    CString中Format函数与格式输入与输出 Format是一个非经常常使用.却又似乎非常烦的方法,下面是它的完整概貌.以供大家查询之用:   格式化字符串forma("%d" ...

随机推荐

  1. TOJ 2939 解救小Q

    描述 小Q被邪恶的大魔王困在了迷宫里,love8909决定去解救她.迷宫里面有一些陷阱,一旦走到陷阱里,就会被困身亡:(,迷宫里还有一些古老的传送阵,一旦走到传送阵上,会强制被传送到传送阵的另一头. ...

  2. Unity5.x发布IOS项目Xcode8免签证调试发布教程

    https://www.jianshu.com/p/b0fb49fbcc14 最近尝试发布一下IOS项目,发现现在发布已经简单很多了,不需要开发者账户也能简单快捷进行真机调试. 调试: 1.准备工作 ...

  3. Python 递归返回树形菜单JSON串 <flask>

    需求:菜单管理功能(增.删.改),多级树形菜单展示 数据库表设计 create table if not exists Menu( id serial primary key , title ) no ...

  4. Find command usage in Linux with excellent examples--reference

    http://www.coolcoder.in/2014/02/find-command-usage-in-linux-with.html find searches the directory tr ...

  5. C#字符串替换_无视大小写

    C#里的string.Replace是不能无视大小写的. 首先想到的是正则表达式,在网上查了下,果然有用正则表达式配合一些逻辑运算,实现无视大小写的字符串替换方法.但是正则表达式的方法用起来很麻烦,实 ...

  6. linq之Capacity(转载)

    出处:博客园 作者:mumuliang 连接:http://www.cnblogs.com/mumuliang/p/3914425.html Capacity 在.NET中List的容量应该只是受到硬 ...

  7. C#+ObjectArx CAD二次开发(2)

    前面开了一个头,这里添加几个功能的实现, //添加图层 private void LoadLayer() { Document acDoc = Application.DocumentManager. ...

  8. sql: 生日赠品中的相关算法

    ---2013年10月9日生日,就以2012年9月1日至2013年8月31日計算 (因為係生日月份前兩個月之最後一天為結算日) DECLARE @birthday datetime,@now date ...

  9. vue授权页面登陆之后返回之前的页面

    import Vue from 'vue'import Router from 'vue-router'Vue.use(Router)import home from "@/pages/ho ...

  10. js实现图片延时加载的原理

    实现原理: 附:(http://www.cnblogs.com/fishtreeyu/archive/2011/03/12/1982067.html) 把所有需要延时加载的图片改成如下的格式: < ...