How to read from standard input line by line?

后端 未结 6 578
走了就别回头了
走了就别回头了 2020-12-22 17:19

What\'s the Scala recipe for reading line by line from the standard input ? Something like the equivalent java code :

import java.util.Scanner; 

public cla         


        
6条回答
  •  离开以前
    2020-12-22 17:41

    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))
    

提交回复
热议问题