我在hdfs中有一个文件夹,其中有两个子文件夹,每个子文件夹大约有30个子文件夹,最后,每个子文件夹都包含xml文件。我想列出所有的xml文件,只给出主文件夹的路径。在本地,我可以使用apache commons-io's FileUtils.listFiles()来做这件事。我已经试过了
FileStatus[] status = fs.listStatus( new Path( args[ 0 ] ) );
但它只列出了前两个子文件夹,并没有更进一步。在hadoop中有什么方法可以做到这一点吗?
发布于 2012-07-05 21:25:13
您将需要使用FileSystem对象并对生成的FileStatus对象执行一些逻辑,以便手动递归到子目录中。
您还可以使用listStatus(Path, PathFilter)方法将PathFilter应用于仅返回xml文件
hadoop FsShell类提供了hadoop fs -lsr命令的示例,该命令是一个递归ls -请参阅the source,在第590行(递归步骤在第635行触发)
发布于 2014-09-03 21:08:47
如果您使用的是hadoop 2.* API,则有更好的解决方案:
Configuration conf = getConf();
Job job = Job.getInstance(conf);
FileSystem fs = FileSystem.get(conf);
//the second boolean parameter here sets the recursion to true
RemoteIterator<LocatedFileStatus> fileStatusListIterator = fs.listFiles(
new Path("path/to/lib"), true);
while(fileStatusListIterator.hasNext()){
LocatedFileStatus fileStatus = fileStatusListIterator.next();
//do stuff with the file like ...
job.addFileToClassPath(fileStatus.getPath());
}
发布于 2015-05-07 19:56:08
/**
* @param filePath
* @param fs
* @return list of absolute file path present in given path
* @throws FileNotFoundException
* @throws IOException
*/
public static List<String> getAllFilePath(Path filePath, FileSystem fs) throws FileNotFoundException, IOException {
List<String> fileList = new ArrayList<String>();
FileStatus[] fileStatus = fs.listStatus(filePath);
for (FileStatus fileStat : fileStatus) {
if (fileStat.isDirectory()) {
fileList.addAll(getAllFilePath(fileStat.getPath(), fs));
} else {
fileList.add(fileStat.getPath().toString());
}
}
return fileList;
}
快速示例:假设您具有以下文件结构:
a -> b
-> c -> d
-> e
-> d -> f
使用上面的代码,您将获得:
a/b
a/c/d
a/c/e
a/d/f
如果您只需要叶(即fileNames),请在else
块中使用以下代码:
...
} else {
String fileName = fileStat.getPath().toString();
fileList.add(fileName.substring(fileName.lastIndexOf("/") + 1));
}
这将提供:
b
d
e
f
https://stackoverflow.com/questions/11342400
复制相似问题