java—hdfs目录中的文件计数

ghhaqwfi  于 2021-06-04  发布在  Hadoop
关注(0)|答案(6)|浏览(434)

在java代码中,我想连接到hdfs中的一个目录,了解该目录中文件的数量,获取它们的名称并想读取它们。我已经可以读取文件,但我不知道如何计数目录中的文件,并获得像普通目录一样的文件名。
为了读取,我使用dfsclient并将文件打开到inputstream中。

ubby3x7f

ubby3x7f1#

要进行快速简单的计数,还可以尝试以下一行:

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

快速解释: grep -E '^-' 或者 egrep '^-' :grep all files:文件以“-”开头,而文件夹以“d”开头; wc -l :行计数。

8wigbo56

8wigbo562#

计数

Usage: hadoop fs -count [-q] <paths>

计算路径下与指定文件模式匹配的目录、文件和字节数。输出列为:dir\u count、file\u count、content\u size file\u name。
带-q的输出列有:quota、remaining\u quata、space\u quota、remaining\u space\u quota、dir\u count、file\u count、content\u size、file\u 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。
您只需使用文件系统并遍历路径中的文件即可。下面是一些示例代码

int count = 0;
FileSystem fs = FileSystem.get(getConf());
boolean recursive = false;
RemoteIterator<LocatedFileStatus> ri = fs.listFiles(new Path("hdfs://my/path"), recursive);
while (ri.hasNext()){
    count++;
    ri.next();
}
ghhkc1vu

ghhkc1vu3#

在命令行上,您可以按以下方式执行。

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

siv3szwd4#

hadoop fs-du[-s][-h][-x]uri[uri…]
显示给定目录中包含的文件和目录的大小,如果只是文件,则显示文件的长度。
选项:

The -s option will result in an aggregate summary of file lengths being displayed, rather than the individual files. Without the -s option, calculation is done by going 1-level deep from the given path.
The -h option will format file sizes in a “human-readable” fashion (e.g 64.0m instead of 67108864)
The -x option will exclude snapshots from the result calculation. Without the -x option (default), the result is always calculated from all INodes, including all snapshots under the given path.
cl25kdpy

cl25kdpy5#

FileSystem fs = FileSystem.get(conf);
Path pt = new Path("/path");
ContentSummary cs = fs.getContentSummary(pt);
long fileCount = cs.getFileCount();
3qpi33ja

3qpi33ja6#

您可以使用以下命令检查该特定目录中的文件计数
hadoop fs -count /directoryPath/* | print $2 | wc -l count : counts the number of files, directories, and bytes under the path print $2 : To print second column from the output wc -l : To check the line count

相关问题