Normal
Normal

Reputation: 1367

Scala: read user input as single string

I need get all user input in stdin as single string in scala 2.12 (supposed the data would copy-pasted by single action), something like this:

please copy data:
word1
word2
word3

And I need get string with following data:

val str = "word1\nword2\nword3"

my current approach is not working, just hanging forever:

import scala.collection.JavaConverters._
val scanner: Iterator[String] = new Scanner(System.in).asScala

val sb = new StringBuilder
while (scanner.hasNext) {
  sb.append(scanner.next())
}
val str = sb.toString()

Although this can print the input:

import scala.collection.JavaConverters._
val scanner: Iterator[String] = new Scanner(System.in).asScala

scanner foreach println

I'm looking for idiomatic way of doing the job

Upvotes: 0

Views: 782

Answers (1)

Mario Galic
Mario Galic

Reputation: 48420

Try

LazyList
  .continually(StdIn.readLine())
  .takeWhile(_ != null)
  .mkString("\n")

as inspired by https://stackoverflow.com/a/18924749/5205022

On my machine I could terminate the input with ^D.

In Scala 2.12 replace LazyList with Stream.

Upvotes: 2

Related Questions