Print a file (Scala)
From LiteratePrograms
In practice, file I/O in Scala is typically done using Java libraries (java.io.File). The native I/O library in Scala is mainly for reading source code.
<<printfile.scala>>= import scala.io.Source object PrintFile { def main (args: Array[String]) = Create Source instance Print each line }
The first step is to create an instance of Source. The companion object has a number of methods that take binary or ASCII buffers, existing files or InputStreams, Strings or Iterables, or URI/URLs. In this particular case, a file name given as argument to PrintFile.main will be used to open a file.
<<Create Source instance>>= Source fromPath args(0)
The getLines method returns an iterator (an optional argument lets the user specify a line separator string; if not given, a platform-dependent separator is used) to the sequence of lines (with separators chopped off) which can be used as any iterator. In this case, we iterate over each line, applying println to it.
<<Print each line>>= getLines() foreach println
Download code |