【发布时间】:2011-01-07 20:27:51
【问题描述】:
我想编写一个 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))))
【问题讨论】: