How to read from standard input line by line?
The most straight-forward looking approach will just use readLine()
which is part of Predef
. however that is rather ugly as you need to check for eventual null value:
object ScannerTest {
def main(args: Array[String]) {
var ok = true
while (ok) {
val ln = readLine()
ok = ln != null
if (ok) println(ln)
}
}
}
this is so verbose, you'd rather use java.util.Scanner
instead.
I think a more pretty approach will use scala.io.Source
:
object ScannerTest {
def main(args: Array[String]) {
for (ln <- io.Source.stdin.getLines) println(ln)
}
}
For the console you can use Console.readLine
. You can write (if you want to stop on an empty line):
Iterator.continually(Console.readLine).takeWhile(_.nonEmpty).foreach(line => println("read " + line))
If you cat a file to generate the input you may need to stop on either null or empty using:
@inline def defined(line: String) = {
line != null && line.nonEmpty
}
Iterator.continually(Console.readLine).takeWhile(defined(_)).foreach(line => println("read " + line))