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. opensuse13.2国内源和设置命令

    ustc-osshttp://mirrors.ustc.edu.cn/opensuse/distribution/13.2/repo/oss/ustc-non-osshttp://mirrors.us ...

  2. linux下安装redis及PHP扩展应用

    一.redis安装 1 下载redis安装包 wget http://redis.googlecode.com/files/redis-2.4.17.tar.gz (若无法下载请手动下载) 2 编译安 ...

  3. Linux VFS机制简析(二)

    Linux VFS机制简析(二) 接上一篇Linux VFS机制简析(一),本篇继续介绍有关Address space和address operations.file和file operations. ...

  4. js消息提示框插件-----toastr用法

     (本文系转载) 因为个人项目中有一个提交表单成功弹出框的需求,从网上找了一些资料,发现toastr这个插件的样式还是不错的.所以也给大家推荐下,但是网上的使用资料不是很详细,所以整理了一下,希望能给 ...

  5. 20个最受欢迎的Linux命令(转)

    本文根据 commandlinefu 网站的历史排名,筛选出了前 20 个得票最高的 Linux 命令.看看你都能熟练使用了吗? 1.以 root 帐户执行上一条命令 sudo !! 2.利用 Pyt ...

  6. javascript:中文等字符转成unicode

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  7. IntelliJ IDEA 2017.3.5 安装 lombok-plugin-0.17 失败,通过网络下载总是超时

    1.问题: IntelliJ IDEA 2017.3.5 安装 lombok-plugin-0.17 失败,通过网络下载总是超时: 2.原因:IntelliJ IDEA 2017.3.5 目前还不支持 ...

  8. Canvas知识点汇总

    本文主要记录Canvas基础知识汇总. 1.Canvas定义 <canvas> 元素是HTML5中的新元素,通过它可以在网页中绘制出所需的图形.<canvas>标签只是图形的容 ...

  9. jquery获取transform里面的值

    用transform的translateX写了一个侧滑效果,如何获取它改变的值是多少呢? 获取translateX值的方法: $('div').css("transform").r ...

  10. 原生js封装十字参考线插件(一)

    需求来源: 拓扑图之机房平面图,显示机房长宽比例尺,房间内标注各种设备间距不易实现,特在机房平面图上层加一个十字参考线 横竖两条线垂直,在鼠标指针处交叉,显示鼠标指针坐标(相对机房平面图的坐标,不是相 ...