Last active
August 31, 2017 09:43
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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