Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JannikArndt/14a8c3844f90bd514cf871cd1c1cb7dc to your computer and use it in GitHub Desktop.
Save JannikArndt/14a8c3844f90bd514cf871cd1c1cb7dc to your computer and use it in GitHub Desktop.
Helper class to write to a file in Scala using just one line and the java.nio package.
object File {
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, OpenOption, Paths, StandardOpenOption}
def append(path: String, txt: String): Unit =
write(path, txt, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.APPEND)
def overwrite(path: String, txt: String): Unit =
write(path, txt, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)
private def write(path: String, txt: String, options: OpenOption*): Unit = {
val filepath = Paths.get(path)
if (filepath.getParent != null)
Files.createDirectories(filepath.getParent)
Files.write(filepath, txt.getBytes(StandardCharsets.UTF_8), options: _*)
}
def read(path: String): String =
scala.io.Source.fromFile(path, "UTF-8").getLines.mkString
}
object Example {
File.append("output/foo.txt", "bar")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment