我想编写一个Scala脚本递归处理目录中的所有文件。对于每个文件,我想看看是否有任何情况下,在X行和X - 2行出现字符串。如果出现类似情况,我想停止处理该文件,并将该文件名添加到地图的文件名到发生次数。我刚开始学习今天斯卡拉,我已经拿到了文件递归码的工作,并且需要一些帮助,搜索字符串,这是我到目前为止有:Scala:最简洁的方式递归解析文件检查多个字符串
import java.io.File
import scala.io.Source
val s1= "CmdNum = 506"
val s2 = "Data = [0000,]"
def processFile(f: File) {
val lines = scala.io.Source.fromFile(f).getLines.toArray
for (i = 0 to lines.length - 1) {
// want to do string searches here, see if line contains s1 and line two lines above also contains s1
//println(lines(i))
}
}
def recursiveListFiles(f: File): Array[File] = {
val these = f.listFiles
if (these != null) {
for (i = 0 to these.length - 1) {
if (these(i).isFile) {
processFile(these(i))
}
}
these ++ these.filter(_.isDirectory).flatMap(recursiveListFiles)
}
else {
Array[File]()
}
}
println(recursiveListFiles(new File(args(0))))
感谢您的回应,我试了一下,但得到一个异常时,它正在处理文件: –
scala.MatchError:List(2010-05-31 17:31:06.015 UTC + 0000 INFO [xxx-HostSy ncThread -Runnable-> HostSync-176666318810351] estation.services.timesync.TimeSync - 与主机'http://www04.xxx.com:80'成功的时间同步:解析后的1275327066705分解到5月31日星期一的系统时间17 :31:06 UTC 2010) at Main $$ anon $ 1 $$ anonfun $ 1.apply(506。Scala:13) at Main $$ anon $ 1 $$ anonfun $ 1.apply(506.scala:13) at scala.collection.Iterator $ class.exists(Iterator.scala:655) at scala.collection.Iterator $ GroupedIterator.exists(Iterator.scala:772) –
@fred,我添加了'case _ => false'来处理短文件。 – huynhjl