OutputFormat 接口实现类
OutputFormat是MapReduce输出的基类,所有实现MapReduce输出都实现了OutputFormat接口。
- 文本输出TextOutputFormat
默认
的输出格式是TextOutputFormat,它把每条记录写为文本行
。它的键值可以是任何类型,因为TextOutputFormat调用toString()方法把他们转换为字符串。 - SequenceFileOutputFormat
将SequenceFileOutputFormat输出作为后续MapReduce任务的输入
。这是一种好的输出格式,因为它的格式紧凑,容易压缩
-
自定义OutputFormat
- 自定义一个类继承FileOutFormat
- 重写RecordWriter,具体重写输出数据的方法write();
继承FileOutFormat
/**
* 自定义输出格式
* 如何输出由自己决定, 可以把数据写入到任何地方.
*/
public class LogWriter extends FileOutputFormat<Text, NullWritable> {
public RecordWriter<Text, NullWritable> getRecordWriter(TaskAttemptContext job) throws IOException, InterruptedException {
return new FilterRecordWriter(job);
}
重写RecordWriter
public class FilterRecordWriter extends RecordWriter<Text, NullWritable> {
private final FSDataOutputStream atguiguOut;
private final FSDataOutputStream otherOut;
public FilterRecordWriter(TaskAttemptContext job) throws IOException {
Configuration conf = job.getConfiguration();
// 1 获取文件系统
FileSystem fs = FileSystem.get(conf);
// 2 创建输出文件路径
Path atguiguPath = new Path("e:/atguigu.log");
Path otherPath = new Path("e:/other.log");
atguiguOut = fs.create(atguiguPath);
otherOut = fs.create(otherPath);
}
@Override
public void write(Text key, NullWritable value) throws IOException, InterruptedException {
if (key.toString().contains("atguigu")) {
atguiguOut.write(key.toString().getBytes());
} else {
otherOut.write(key.toString().getBytes());
}
}
@Override
public void close(TaskAttemptContext context) throws IOException, InterruptedException {
// 关闭资源
IOUtils.closeStream(atguiguOut);
IOUtils.closeStream(otherOut);
}
}
jobDriver设置
// 要将自定义的输出格式组件设置到job中
job.setOutputFormatClass(FilterOutputFormat.class);