OutputFormat是MapReduce输出的基类,所有实现MapReduce输出都实现了OutputFormat接口。默认输出格式是TextOutputFormat
当需要输出数据到MySQL/Hbase/Elasticsearch等存储框架时需要自定义OutputFormat。
定义OutputFormat步骤:
1.自定义一个类继承FileOutputFormat
2.改写RecordWriter,具体改写输出数据的方法wtite()
实例:
(1)编写LogMapper类
public class LogMapper extends Mapper{ @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { context.write(value,NullWritable.get()); } }
(2)编写LogReducer类
public class LogReducer extends Reducer{ @Override protected void reduce(Text key, Iterable values, Context context) throws IOException, InterruptedException { for (NullWritable value : values) { context.write(key,NullWritable.get()); } } }
(3)自定义一个LogOutputFormat类
public class LogOutputFormat extends FileOutputFormat{ @Override public RecordWriter getRecordWriter(TaskAttemptContext job) throws IOException, InterruptedException { LogRecordWriter logRecordWriter = new LogRecordWriter(job); return logRecordWriter; } }
(4)编写LogRecordWriter类
public class LogRecordWriter extends RecordWriter{ private FSDataOutputStream atguiguout; private FSDataOutputStream otherout; public LogRecordWriter(TaskAttemptContext job) { try { FileSystem fs = FileSystem.get(job.getConfiguration()); atguiguout = fs.create(new Path("F:\atguigu.log")); otherout = fs.create(new Path("F:\other.log")); } catch (Exception e) { e.printStackTrace(); } } @Override public void write(Text text, NullWritable nullWritable) throws IOException, InterruptedException { String log = text.toString(); if (log.contains("atguigu")){ atguiguout.writeBytes(log+"n"); }else{ otherout.writeBytes(log+"n"); } } @Override public void close(TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException { IOUtils.closeStreams(otherout); IOUtils.closeStreams(atguiguout); } }
(5)编写LogDriver类
public class LogDriver {
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf);
job.setJarByClass(LogDriver.class);
job.setMapperClass(LogMapper.class);
job.setReducerClass(LogReducer.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(NullWritable.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(NullWritable.class);
job.setOutputFormatClass(LogOutputFormat.class);
FileInputFormat.setInputPaths(job,new Path("F:\inputoutputformat"));
FileOutputFormat.setOutputPath(job,new Path("F:\of"));
job.waitForCompletion(true);
}
}



