我正在监视hdfs
中的目录,如果有文件放入其中,我想检索进入目录的文件的名称并应用模式匹配,以便根据名称对它们进行排序到目前为止我有能够检索文件路径。它给我文件名但我不知道如何进一步进行模式匹配
import org.apache.hadoop.mapreduce.lib.input.{FileSplit, TextInputFormat}
import org.apache.spark.rdd.{NewHadoopRDD}
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.hadoop.io.LongWritable
import org.apache.hadoop.io.Text
object path {
def main(args: Array[String]) {
val conf = new SparkConf().setAppName("Simple Application").setMaster("local")
val sc = new SparkContext(conf)
val fc = classOf[TextInputFormat]
val kc = classOf[LongWritable]
val vc = classOf[Text]
val path :String = "/home/hduser/Desktop/foldername"
val text = sc.newAPIHadoopFile(path, fc ,kc, vc, sc.hadoopConfiguration)
println("++++++++++++++ "+text)
val linesWithFileNames = text.asInstanceOf[NewHadoopRDD[LongWritable, Text]].mapPartitionsWithInputSplit((inputSplit, iterator) => {
val file = inputSplit.asInstanceOf[FileSplit]
println(">>>>>>>>>>>>>>>> "+file.getPath)
iterator.map(tup => (file.getPath, tup._2))
}
)
linesWithFileNames.collect()
}
}
这给了我这样的道路
的 /home/hduser/Desktop/folder_name/XYZ_123_pqr_abc_FILENAME
我希望根据文件名开始应用模式匹配....这里它将基于 XYZ 。
任何帮助将不胜感激。
答案 0 :(得分:0)
我认为你不够具体。从你的问题的上下文我假设XYZ是数字,你打算按这些数字排序文件,如果是这种情况考虑以下例子:
val matchStart = """^(\d{3})""".r.unanchored
val number = file match {
case matchStart(number, _*) => number.toInt
case _ => ???//error handling, not necessarily unimplemented error
}
现在从文件名开头提取了数字,你可以进行排序等。 的修改
评论中的以下信息回答类似:
val matchStart = """^([a-zA-Z1-9]{3})""".r.unanchored
val prefix = file match {
case matchStart(a, _*) => a
case _ => ???//error handling, not necessarily unimplemented error
}
提取前缀后,您可以随意执行任何操作。