在文本文件中搜索术语和打印行

时间:2014-11-20 04:17:59

标签: scala text-files

文件名是searcher.scala,我希望能够输入:

scala searcher.scala "term I want to find" "file I want to search through" "new file with new lines"

我试过这段代码,但一直说我有一个空的迭代器

import java.io.PrintWriter

val searchTerm = args(0)
val input = args(1) 
val output = args(2)

val out = new PrintWriter(output);

val listLines = scala.io.Source.fromFile(input).getLines

for (line <- listLines) 
{ 
    { out.println("Line: " + line) }

    def term (x: String): Boolean = {x == searchTerm} 
    val newList = listLines.filter(term)
    println(listLines.filter(term))
}
out.close;

1 个答案:

答案 0 :(得分:1)

你有迭代器listLines并且你读了几次但是迭代器是一次性对象:

  • for (line <- listLines)
  • val newList = listLines.filter(term)
  • println(listLines.filter(term))

您需要修改代码以避免重复使用迭代器。