Scala provides a few extensions to Java’s IO library.
Text
Output
print()
and println()
: the latter adds a newline to the end.
printf()
supports C-style format string.
Input
readLine()
read a line of input. It can specify a prompt string.
readInt(), readDouble()
etc can read a proper type value, but no prompt string can be supplied.
File
Input
- Open a file: use
scala.io.Source
object:val source = Source.fromFile(filename, encoding)
. Filename can be a string or ajava.io.File
. Encoding can be omitted. - Read from other sources: use
Source.fromURL(URL, encoding)
,Source.fromString(s)
, andSource.stdin
to read from URL, String, and standard input. - Read lines:
val lineIterator = source.getLines
. The result is an iterator. It can be used to process line-by-line in a for loop, or convert to array/buffer usingtoArray
/toBuffer
. - Read whole file:
source.mkString
. - Read character: use
source
object directly. If you want to peek without moving the header, callval iter = source.buffered
to get a buffered object. - Split by token:
val tokens = source.mkString.split("\\s+")
splits by whitespace.
Binary files: Scala has no specific way to read binary files. Use Java library instead.
Output
To write a text filem use java.io.PrintWriter
.
Directories
Fall back to Java libraries.
Serialization
@SerialVersionUID(0L) class Person extends Serializable
. Then to send an object, use instance of ObjectOutputStream
and call writeObject(obj)
method. To receive an object, use instance of ObjectInputStream
and call in.readObject().asInstanceOf[Class]
to convert to the right type.
Scala collections are serializable.