HDFS目录中的文件计数

在Java代码中,我想连接到HDFS中的目录,了解该目录中的文件数量,获取它们的名称并想要读取它们。 我已经可以读取文件,但我无法弄清楚如何计算目录中的文件并获取像普通目录这样的文件名。

为了阅读我使用DFSClient并将文件打开到InputStream中。

计数

Usage: hadoop fs -count [-q]  

计算与指定文件模式匹配的路径下的目录,文件和字节数。 输出列为:DIR_COUNT,FILE_COUNT,CONTENT_SIZE FILE_NAME。

带-q的输出列为 QUOTA,REMAINING_QUATA,SPACE_QUOTA,REMAINING_SPACE_QUOTA,DIR_COUNT,FILE_COUNT,CONTENT_SIZE,FILE_NAME。

例:

 hadoop fs -count hdfs://nn1.example.com/file1 hdfs://nn2.example.com/file2 hadoop fs -count -q hdfs://nn1.example.com/file1 

退出代码:

成功时返回0,错误时返回-1。

您只需使用FileSystem并迭代路径中的文件即可。 这是一些示例代码

 int count = 0; FileSystem fs = FileSystem.get(getConf()); boolean recursive = false; RemoteIterator ri = fs.listFiles(new Path("hdfs://my/path"), recursive); while (ri.hasNext()){ count++; ri.next(); } 
 FileSystem fs = FileSystem.get(conf); Path pt = new Path("/path"); ContentSummary cs = fs.getContentSummary(pt); long fileCount = cs.getFileCount(); 

你也可以尝试:

 hdfs dfs -ls -R /path/to/your/directory/ | grep -E '^-' | wc -l 

在命令行上,您可以执行以下操作。

  hdfs dfs -ls $parentdirectory | awk '{system("hdfs dfs -count " $6) }'