`
退役的龙弟弟
  • 浏览: 457446 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

HDFS中PathFilter类对路径进行过滤

 
阅读更多

1、定义类实现PathFilter接口

package com.ru.hadoop.wordcount;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathFilter;

/**
 * 文件路径过滤
 * @author nange
 *
 */
public class MyFilePathFileter implements PathFilter{
	//需要读取文件名必须包含fileName字符串
	private String fileName;
	
	public MyFilePathFileter(String fileName){
		this.fileName = fileName;
	}

	/**
	 * @param path :文件路径 如:hdfs://localhost:9000/hdfs/test/wordcount/in/word.txt
	 */
	@Override
	public boolean accept(Path path) {
		boolean res = false;
		if(path.toString().indexOf(fileName) != -1){
			res = true;
		}
		System.out.println("path = " + path + "过滤结果:" + res);
		return res;
	}

}

 2、使用FileSystema提供globStatus()方法对文件路径进行过滤

/**
	 * 对文件路径进行过滤
	 * FileSystema提供globStatus()方法对文件路径进行过滤,这里的路径必须是hdfs路径
	 * 
	 * @param in : 使用通配符 如:hdfs://localhost:9000/hdfs/test/wordcount/in/*
	 * @throws IOException 
	 */
	public String filePaths(String in) throws IOException{
		StringBuilder sb = new StringBuilder();
		//globStatus()方法返回与路径想匹配的所有文件的FileStatus对象数组,并按路径排序。
		FileStatus[] fss = fs.globStatus(new Path(in), new MyFilePathFileter("in/word"));
		Path[] paths = FileUtil.stat2Paths(fss);
		if(paths != null){
			for(Path path : paths){
				sb.append(path.toString() + ",");
			}
		}
		int index = sb.toString().lastIndexOf(",");
 		if(index != -1){
 			System.out.println("过滤后的文件路径:" + sb.toString().substring(0, index));
 			return sb.toString().substring(0, index);
		}
		
		return null;
	}

 3、作业多路径输入

fileInPaths:字符串使用","分割.如:hdfs://localhost:9000/hdfs/test/wordcount/in/word.txt,hdfs://localhost:9000/hdfs/test/wordcount/in/word2.txt

FileInputFormat.addInputPaths(job, fileInPaths);//多输入路径

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics