spark多文件输出

1.因为spark是用hadoop的api进行输出的,MultipleOutputFormat是hadoop用于支持多文件输出的,所以自定义一个MultipleOutputFormat类

import java.io.IOException;

import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.RecordWriter;
import org.apache.hadoop.mapred.TextOutputFormat;
import org.apache.hadoop.mapred.lib.MultipleOutputFormat;
import org.apache.hadoop.util.Progressable;

public class MyMultipleOutput extends MultipleOutputFormat<String, String>{
	 private TextOutputFormat<String, String> output = null;

	@Override
	protected String generateFileNameForKeyValue(String key, String value,
			String name) {
		String[] split = key.split(",");
		String device=split[0];
		String year=split[1].substring(0,4);
		String month=split[1].substring(5,7);
		String day=split[1].substring(8,10);
		/*name是reduce任务默认文件名,注意如果这里返回的文件名不追加name,
		*就会造成多个reduce获取到的文件名都是day,多个reduce写一个文件,文件内容只会有一个reduce输出的内容
		*/
		return device+"/"+year+"/"+month+"/"+day+"/"+name;
		
	}

	@Override
	protected RecordWriter<String, String> getBaseRecordWriter(FileSystem fs,
			JobConf job, String name, Progressable arg3) throws IOException {
		if (output == null) {
	          output = new TextOutputFormat<String, String>();
	        }
	        return output.getRecordWriter(fs, job, name, arg3);
	}

}

2.pair类型RDD的saveAsHadoopFile方法进行输出

deviceDateKeyPair.saveAsHadoopFile("d://multioutput/", NullWritable.class, String.class, MyMultipleOutput.class);




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值