Scala 工具組

如何撰寫檔案?

語言

您可以在單一行中要求整個工具組

//> using toolkit latest

或者,您也可以只要求 OS-Lib 的特定版本

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

在您的 build.sbt 中,您可以新增對工具組的相依性

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

或者,您也可以只要求 OS-Lib 的特定版本

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

在您的 build.sc 檔案中,您可以新增對工具組的相依性

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

或者,您也可以只要求 OS-Lib 的特定版本

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

一次撰寫一個檔案

os.write 將提供的字串寫入新檔案

val path: os.Path = os.temp.dir() / "output.txt"
os.write(path, "hello\nthere\n")
println(os.read.lines(path).size)
// prints: 2

覆寫或附加

os.write 檔案已存在時會擲回例外

os.write(path, "this will fail")
// this exception is thrown:
// java.nio.file.FileAlreadyExistsException

為避免此情況,請使用 os.write.over 取代現有內容。

您也可以使用 os.write.append 在結尾新增內容

os.write.append(path, "two more\nlines\n")
println(os.read.lines(path).size)
// prints: 4

此頁面的貢獻者