本文用于复习《Hadoop权威指南》第三章后半部分内容
代码来自于书中,仅有少部分修改,主要是为了回忆起来方便
在文章eclipse实现word count中就有关于如何在eclipse中开发hadoop项目,链接如下Eclipse实现Hadoop WordCount
利用FileSystem的listStatus方法来读取文件和目录的元数据,再用stat2path方法讲status数组转为path数组。
这里用一种与之前不同的路径设置方法(虽然其实是与书上一样的),在run configuration中添加参数
hdfs://localhost:9000/ 和hdfs://localhost:9000/user/wyh/
public class ListStatus {
public static void main(String[] args) throws Exception {
String uri = args[0];
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(URI.create(uri), conf);
Path[] paths = new Path[args.length];
for (int i = 0; i < paths.length; i++) {
paths[i] = new Path(args[i]);
}
FileStatus[] status = fs.listStatus(paths);
Path[] listedPaths = FileUtil.stat2Paths(status);
for (Path p : listedPaths) {
System.out.println(p);
}
}
}
书上给出了一个RegexExcludePathFilter类实现了PathFilter接口,用于排除一个正则表达式路径,也觉得挺有趣的,但是没有给具体实现排除的代码,在这里写了一个TestFilter类来实现一下。
首先把2016.12.01.txt和2016.12.02.txt放到分布式系统中,可以看到在去掉RegexExcludePathFilter的时候会两个文件都显示,直接运行则会显示路径+2016.12.02.txt。
public class TestFilter {
public static void main(String[] args) throws Exception {
String uri = "hdfs://localhost:9000/";
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(URI.create(uri), conf);
FileStatus[] status =fs.globStatus(new Path("hdfs://localhost:9000/user/wyh/2016.*.*")
,new RegexExcludePathFilter("hdfs://localhost:9000/user/wyh/2016.12.01.*"));
// ,new RegexExcludePathFilter("hdfs://localhost:9000/user/wyh/2016.12.01.*")
Path[] listedPaths = FileUtil.stat2Paths(status);
for (Path p : listedPaths) {
System.out.println(p);
}
}
}