利用PathFilter上传多个本地的文件

来源:互联网 发布:守望先锋数据app 编辑:程序博客网 时间:2024/05/01 02:02

介绍了上传本地的多个文件,其中应用了PathFilter接口进行了文件的类型的过滤。上传特定的后缀的文件。

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.hadoop.conf.Configuration;
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;

public class CopyAll {
public static void main(String[] args) throws URISyntaxException, IOException {
//获取系统的配置
Configuration conf = new Configuration() ;
URI uri = new URI(“hdfs://hadoop:9000”) ;
//获取HDFS的文件系统配置
FileSystem fs = FileSystem.get(uri, conf) ;
//获取本地文件系统的配置
FileSystem local = FileSystem.getLocal(conf) ;
//创建一个本地文件目录的实例,设置为源目录集合
Path path1 = new Path(“D://demo/*”) ;
//创建一个HDFS的文件目录实例,为目的路径
Path dst = new Path(“hdfs://hadoop:9000/copyAll/”) ;
//声明一个匹配模式的实例对象找出所有的后缀为“.txt”的文件
RegexPathFilter filter = new RegexPathFilter(“^.*txt$”);
//本地文件实例对象local调用globStatus(Path f,PathFilter p)方法,
//返回特定的后缀文件
FileStatus[] listFile = local.globStatus(path1, filter);
//返回Path对象的数组
Path[] listPath = FileUtil.stat2Paths(listFile);
//循环遍历对象数组
for(Path p:listPath){
//输出文件的绝对路径
fs.copyFromLocalFile(p, dst);
}
//释放资源
local.close();
fs.close();
}

public static class RegexPathFilter implements PathFilter{    /*     * PathFilter是一个接口,只包含了一个accept(Path path)方法     */    private String regex ;    public RegexPathFilter(String regex){         this.regex = regex ;    }    @Override    public boolean accept(Path path) {        boolean flag = path.toString().matches(regex) ;        return flag;    }}

}

0 0
原创粉丝点击