Scala IOException on a closed reader
Reading a closed BufferedReader raises an IOException on the JVM.
A simple example
IOException on a closed reader
- Start with A reader has already been closed
- Do this Try another read
- Result Read fails
Syntax
reader.readLine()
Run these examples in Scala
Save one example at a time as Lesson.scala. Use Scala 2.13 on JDK 21.
scalac Lesson.scala
scala LessonRead from a finished receipt import
A receipt importer closes its reader at the end of a batch. If the preview screen asks for another line through that reader, the application needs to detect the stale handle and open a new reader for the next batch.
import java.io.BufferedReader
import java.io.StringReader
import java.io.IOException
object Lesson {
def main(args: Array[String]): Unit = {
val reader = new BufferedReader(new StringReader("Receipt"))
reader.close()
try {
println(reader.readLine())
} catch {
case problem: IOException =>
println("Open a new reader")
}
}
}
Open a new reader
Closing the reader makes it unusable for the preview even though the original text still exists.
Read the first rehearsal note
The music desk has just opened a reader containing a short note. Read the next character from the stream. A previously closed stream prompts the desk to reopen the source.
Revisit a completed import
A receipt reader was closed before the operator requested the next character. Read the next character from the stream. A previously closed stream prompts the desk to reopen the source.
What to watch for
Use the reader within its lifetime. A general I/O failure may have other causes.