The Scala Toolkit

How to read a file?

Language

You can require the entire toolkit in a single line:

//> using toolkit latest

Alternatively, you can require just a specific version of OS-Lib:

//> using dep com.lihaoyi::os-lib:0.9.1

In your build.sbt, you can add a dependency on the toolkit:

lazy val example = project.in(file("."))
  .settings(
    scalaVersion := "3.3.3",
    libraryDependencies += "org.scala-lang" %% "toolkit" % "0.1.7"
  )

Alternatively, you can require just a specific version of OS-Lib:

libraryDependencies += "com.lihaoyi" %% "os-lib" % "0.9.1"

In your build.sc file, you can add a dependency on the Toolkit:

object example extends ScalaModule {
  def scalaVersion = "3.3.3"
  def ivyDeps =
    Agg(
      ivy"org.scala-lang::toolkit:0.1.7"
    )
}

Alternatively, you can require just a specific version of OS-Lib:

ivy"com.lihaoyi::os-lib:0.9.1"

Reading a file

Supposing we have the path to a file:

val path: os.Path = os.root / "usr" / "share" / "dict" / "words"

Then we can slurp the entire file into a string with os.read:

val content: String = os.read(path)

To read the file as line at a time, substitute os.read.lines.

We can find the longest word in the dictionary:

val lines: Seq[String]  = os.read.lines(path)
println(lines.maxBy(_.size))
// prints: antidisestablishmentarianism

There’s also os.read.lines.stream if you want to process the lines on the fly rather than read them all into memory at once. For example, if we just want to read the first line, the most efficient way is:

val lineStream: geny.Generator[String] = os.read.lines.stream(path)
val firstLine: String = lineStream.head
println(firstLine)
// prints: A

OS-Lib takes care of closing the file once the generator returned by stream is exhausted.

Contributors to this page: