The Scala Toolkit
How to write a file?
Language
Info: JavaScript is currently disabled, code tabs will still work, but preferences will not be remembered.
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.11.3
In your build.sbt
, you can add a dependency on the toolkit:
lazy val example = project.in(file("."))
.settings(
scalaVersion := "3.4.2",
libraryDependencies += "org.scala-lang" %% "toolkit" % "0.7.0"
)
Alternatively, you can require just a specific version of OS-Lib:
libraryDependencies += "com.lihaoyi" %% "os-lib" % "0.11.3"
In your build.sc
file, you can add a dependency on the Toolkit:
object example extends ScalaModule {
def scalaVersion = "3.4.2"
def ivyDeps =
Agg(
ivy"org.scala-lang::toolkit:0.7.0"
)
}
Alternatively, you can require just a specific version of OS-Lib:
ivy"com.lihaoyi::os-lib:0.11.3"
Writing a file all at once
os.write
writes the supplied string to a new file:
val path: os.Path = os.temp.dir() / "output.txt"
os.write(path, "hello\nthere\n")
println(os.read.lines(path).size)
// prints: 2
Overwriting or appending
os.write
throws an exception if the file already exists:
os.write(path, "this will fail")
// this exception is thrown:
// java.nio.file.FileAlreadyExistsException
To avoid this, use os.write.over
to replace the existing
contents.
You can also use os.write.append
to add more to the end:
os.write.append(path, "two more\nlines\n")
println(os.read.lines(path).size)
// prints: 4