HDFS 文件合并

将本地小文件合并上传到HDFS文件系统中。

一种方法可以现在本地写一个脚本,先将一个文件合并为一个大文件,然后将整个大文件上传,这种方法占用大量的本地磁盘空间;

另一种方法如下,在复制的过程中上传。

package mergerfiles;

import java.io.IOException;

import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

public class PutMerge {

	public static void putMergeFunc(String localDir,String fsFile) throws IOException{
		Configuration conf = new Configuration();
		conf.set("fs.default.name", "hdfs://localhost:9000");
		FileSystem fs = FileSystem.get(conf);			//fs 是HDFS文件系统
		FileSystem local = FileSystem.getLocal(conf);	//本地文件系统
		
		Path localdir = new Path(localDir);
		Path hdfsFile = new Path(fsFile);
		
		FileStatus[] status = local.listStatus(localdir);//得到输入路径
		FSDataOutputStream out = fs.create(hdfsFile);	 //在HDFS 上创建输出文件
		for(FileStatus st: status){
			Path temp = st.getPath();
			FSDataInputStream in = local.open(temp);
			IOUtils.copyBytes(in, out, 4096, false);	//读取in流中的内容放入out
			in.close();									//完成后,关闭当前文件输入流
		}
		out.close();
	}
	
	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		String sourceFile = "";
		String targetFile = "";
		if(args.length<2){
			sourceFile = "/opt/201211 1330/20121101";
			targetFile = "/import/1/20121101/20121101.txt";
		}else{
			sourceFile = args[0];
			targetFile = args[1];
		}
		putMergeFunc(sourceFile, targetFile);
	}

}

引自 : http://www.cnblogs.com/dandingyy/archive/2013/03/08/2950720.html

转载于:https://my.oschina.net/u/999578/blog/172881

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值