将本地小文件合并上传到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