hadoop自定义文件输出格式

           自定义文件的输出格式相对于输入格式来说就简单一些,在自己的输出格式里面实现RecordWriter接口即可,关键是同步写方法的实现可以把key,value的输出控制的很灵活,看看例子吧:

public class ImageOutputFormat extends TextOutputFormat<Text, DistanceVector> {		
    protected static class Writer extends RecordWriter<Text, DistanceVector> {
        private LineRecordWriter<Text, Text> w;
        public Writer(DataOutputStream dos, String codec) {
            w = new LineRecordWriter<Text, Text>(dos, codec);
        }
        public Writer(DataOutputStream dos) {
            w = new LineRecordWriter<Text, Text>(dos);
        }
    //  这里控制自己的输出style
        public synchronized void write(Text key, DistanceVector value)
                throws IOException {
                StringBuffer sb = new StringBuffer();
                
                System.out.println(value.getV2());
            	java.util.Iterator<Double> iter=value.getV1().iterator();
            	while(iter.hasNext())
            	{
            		sb.append(iter.next());new Text(key.toString());
            		sb.append(",");
            	}
                sb.append(" distance:"+value.getV2());
            
           
             w.write(new Text(key), new Text(sb.substring(0,
                    sb.length() - 1) + "\n"));
        }

        @Override
        public void close(TaskAttemptContext context) throws IOException,
                InterruptedException {
            w.close(context);
        }

        ;
    }

    @Override
    public RecordWriter<Text, DistanceVector> getRecordWriter(
            TaskAttemptContext job) throws IOException, InterruptedException {
        Configuration conf = job.getConfiguration();
        boolean isCompressed = getCompressOutput(job);
        String keyValueSeparator = conf.get(
                "mapred.textoutputformat.separator", "\t");//key value的分隔符自己可以设置
        CompressionCodec codec = null;
        String extension = "";
        if (isCompressed) {
            Class<? extends CompressionCodec> codecClass = getOutputCompressorClass(
                    job, GzipCodec.class);
            codec = (CompressionCodec) ReflectionUtils.newInstance(codecClass,
                    conf);
            extension = codec.getDefaultExtension();
        }
        Path file = getDefaultWorkFile(job, extension);
        FileSystem fs = file.getFileSystem(conf);
        if (!isCompressed) {
            FSDataOutputStream fileOut = fs.create(file, false);
            return new Writer(fileOut, keyValueSeparator);
        } else {
            FSDataOutputStream fileOut = fs.create(file, false);
            return new Writer(new DataOutputStream(codec.createOutputStream(fileOut)), keyValueSeparator);
        }
    }

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值