Java API 读取HDFS目录下的所有文件

/**
 * 获取1号店生鲜食品的分类id字符串
 * @param filePath
 * @return
 */
public String getYHDSXCategoryIdStr(String filePath) {
	final String DELIMITER = new String(new byte[]{1});
	final String INNER_DELIMITER = ",";
	
	// 遍历目录下的所有文件
	BufferedReader br = null;
	try {
		FileSystem fs = FileSystem.get(new Configuration());
		FileStatus[] status = fs.listStatus(new Path(filePath));
		for (FileStatus file : status) {
			if (!file.getPath().getName().startsWith("part-")) {
				continue;
			}
			
			FSDataInputStream inputStream = fs.open(file.getPath());
			br = new BufferedReader(new InputStreamReader(inputStream));
			
			String line = null;
			while (null != (line = br.readLine())) {
				String[] strs = line.split(DELIMITER);
				String categoryId = strs[0];
				String categorySearchName = strs[9];
				if (-1 != categorySearchName.indexOf("0-956955")) {
					yhdsxCategoryIdStr += (categoryId + INNER_DELIMITER);
				}
			}// end of while
		}
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		try {
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	return yhdsxCategoryIdStr;
}


HDFS上的目录、文件:

-bash-3.2$ hadoop fs -ls /user/hive/warehouse/category
Found 2 items
-rw-r--r--   2 basicdata supergroup          0 2014-08-18 01:05 /user/hive/warehouse/category/_SUCCESS
-rw-r--r--   2 basicdata supergroup    1117233 2014-08-18 01:05 /user/hive/warehouse/category/part-m-00000

文件内容:

-bash-3.2$ hadoop fs -cat /user/hive/warehouse/category/part-* | more
52880000052880杂粮组合51621010-5135-5162-5288:食品-粮油-杂粮组合011
9726780009726787茶具19650290040-950340-965029-972678:家居-餐具水具-茶具1011
9701550009701557菲士康196046510null0-960464-960465-970155:隐形眼镜(药网)-普通隐形眼镜-菲士康1011
9702350009702356生活服务000180-970235:生活服务011
9702360009702367SIM卡9635241030-957328-963524-970236:手机通讯/数码电器-运营商-SIM卡011
9737840009737842鞋包配饰97377810null0-960665-960768-973775-973778-973784:1号礼品中心-时尚创意礼品-定制品-个性定制-鞋包配饰011
5315T602个人清洁5183190null0-5134-5183-5315:厨卫清洁-清洁剂-个人清洁111
5316T603家用清洁5183190null0-5134-5183-5316:厨卫清洁-清洁剂-家用清洁111
5317UD02蛋制品1516110null0-5135-5161-5317:食品饮料-腌制品1-蛋制品1111
5318UD030肉制品5161180null0-5135-5161-5318:食品饮料-腌制品-肉制品111

你可能感兴趣的:([大数据]HDFS)