您可以将您的解决方案与命令wholeTextFiles() 结合使用。这只是一个技巧,但它可能对你有好处。
根据official spark documentation,命令wholeTextFiles() 允许您读取包含多个小文本文件的目录,并将每个文件作为filename/content 对返回。这与textFile() 形成对比,textFile() 在每个文件中每行返回一条记录。
您可以从文件夹路径的原始数组开始,创建一组 key/value RDD-s,每个 RDD-s 代表 filename/content 数据中整个文件夹的名称和内容格式。
考虑以下起始场景:
Folder 1 (location > hdfs:\\Folder1)
- File01 (location > hdfs:\\Folder1\File01) > Hello this is the content of file 01
- File02 (location > hdfs:\\Folder1\File02) > Hello this is the content of file 02
Folder 2 (location > hdfs:\\Folder1)
- File03 (location > hdfs:\\Folder2\File03) > Hello this is the content of file 03
- File04 (location > hdfs:\\Folder2\File04) > Hello this is the content of file 04
假设你有一个 array 由 strings 组成,其中包含每个文件夹的名称,看起来像
DirArray[0]: "hdfs:\\Folder1"
DirArray[1]: "hdfs:\\Folder2"
下一步是为每个文件夹创建一个 RDD。每个 RDD 将以filename/content 格式表示整个文件名列表及其内容。为此,您可以遍历 path 数组并为每个元素调用命令 wholeTextFiles()。它将包括以下内容:
For each element in DirArray > wholeTextFiles("hdfs:\\FolderN")
每个生成的 RDD 如下所示:
firstFolderRDD (key/value):
- "hdfs:\\Folder1\File01" > "Hello this is the content of file 01
- "hdfs:\\Folder1\File02" > "Hello this is the content of file 02
此时,将有两种选择:
a) 将每个 RDD 存储在 类数组 结构中,稍后计算其元素
b) 在每个 RDD 生成时计算它们的元素(在前面的 for each 部分中)。
需要注意的是,这种方法只推荐用于一组小文件,主要是因为新创建的 RDD-s 的每一行都将包含它所代表的文件的全部内容。