0

My code is simple.
When I execute Main function, I can enter number for only once.
If I enter second number, IOException: Stream closed occurs.
Can you explain why?

import java.io.*

fun main() {
    for (i in 0 until 5)
        val number = readLine().toInt()
}

fun readLine(): String {
    BufferedReader(InputStreamReader(System.`in`)).use { reader ->
        return reader.readLine()
    }
}
  • The error explains itself, the stream is closed. `use` calls `.close()` on the resources after the block end. So `System.in` is closed, which [cannot be reopen](https://stackoverflow.com/questions/27286690/in-java-is-it-possible-to-re-open-system-in-after-closing-it) – Ricky Mo Jan 13 '22 at 01:37
  • I found BufferedReader's InputSream is null. But when I call readLine(), won't InputStream be recreated? If not, is there any way to reuse readLine function? – Joon Hee Song Jan 13 '22 at 02:13

0 Answers0