您的位置:首页 > 运维架构

在hadoop下的多个文件合并

2016-04-05 15:15 1046 查看
本篇文章主要是对多文件合并问题的一个程序展示,主要对程序进行了深入的分析。

import java.net.URI;

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.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathFilter;
import org.apache.zookeeper.common.IOUtils;

public class copyBig {
public static void main(String[] args) throws Exception {
//list()方法的调用
list() ;
}
public static void list() throws Exception{
//获取文件系统配置
Configuration conf = new Configuration() ;
URI uri = new URI("hdfs://hadoop:9000") ;
//获取本地链接Linux下的系统配置
FileSystem fs = FileSystem.get(uri, conf) ;
//获取windows本地的文件配置
FileSystem local = FileSystem.getLocal(conf) ;
//文件的过滤,过滤掉在/demo/目录下的末尾是svn的文件
FileStatus[] listdir = local.globStatus(new Path("e://demo/"), new RegexExcludePathFilter("^.*svn$"));
//将目录/demo/下的所有文件生成对应的路径例如:e://demo/2016-4-5/
Path[]  listPath = FileUtil.stat2Paths(listdir) ;
//创建输入,输出文件的对象
FSDataInputStream  in = null ;
FSDataOutputStream out = null ;
/*
* 程序中包含两个for循环,其中第一个for循环是一次遍历e://demo/*中的文件夹,在之后的执行中作为
* 路径,其中的文件夹的名字作为之后上传的文件的名字例如e://demo/2016-4-5/*下的文件,上传之后的
* 文件的名字是hdfs://hadoop:9000/copyAll/201645.txt
* 第二个for循环,就是将多个文件在的多次追加
*
*/
for(Path list:listPath){
//获取目录的名字,将名字改变为e://demo/201645
String fileName = list.getName().replace("-","");
//返回目录下的文件的路径对象
FileStatus[] localFile = local.globStatus(new Path(list+"/*"),new RegexFilePathFilter("^.*txt$")) ;
//获取文件的路径,例如其中一条:e://demo/201645/ont.txt
Path[] localPath = FileUtil.stat2Paths(localFile) ;
//声明一个hdfs的对象作为目标对象
Path block = new Path("hdfs://hadoop:9000/copyAll/"+fileName+".txt") ;
out = fs.create(block);
for(Path p :localPath){
in = local.open(p) ;
//将路径下的文件以此上传
IOUtils.copyBytes(in, out, 4096, false);
in.close();
}
if(out != null){
out.close();

9b17
}
}
}

public static class RegexExcludePathFilter implements PathFilter{

private String regex ;
public RegexExcludePathFilter(String regex){
this.regex = regex ;
}
@Override
public boolean accept(Path path) {
boolean flag = path.toString().matches(regex) ;
//返回不包含所传过来的文件类型
return !flag;
}
}

public static class RegexFilePathFilter implements PathFilter{
private String regex ;
public RegexFilePathFilter(String regex){
this.regex = regex ;
}
@Override
public boolean accept(Path path) {
// TODO Auto-generated method stub
boolean flag = path.toString().matches(regex) ;
//返回包含所传过来的文件类型
return flag;
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: