Last active
August 29, 2015 14:01
-
-
Save ericpony/fbf381b5bb687b8be5be to your computer and use it in GitHub Desktop.
Several ways to write text to file
This file contains 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
def using[A <: {def close(): Unit}, B](res: A)(op: A => B): B = try op(res) finally res.close | |
def writeToFile(path: String, data: String): Unit = | |
using(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path), "UTF-8")))(_.write(data)) | |
def appendToFile(path: String, data: String): Unit = | |
using(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path, true), "UTF-8")))(_.write(data)) | |
def printToFile(path: String)(op: PrintWriter => Unit): Unit = | |
using(new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path), "UTF-8"))))(op) | |
//Example usage: | |
printToFile("filename")(p => {List("line1","line2","line3").foreach(p.println)}) | |
/** | |
* One-liners to write a line | |
* */ | |
import sys.process._; "echo Hello world!" #> new java.io.File("filename") ! // works only in *nix | |
Some(new java.io.PrintWriter("filename", "UTF-8")).foreach{ p => try p.write("text") finally p.close } | |
/** | |
* Make it reusable | |
* */ | |
def saveText(filename: String, text: String): Unit = { | |
val pw = java.io.PrintWriter(new java.io.File(filename), "UTF-8") | |
try pw.write(text) finally pw.close | |
} | |
/** | |
* More general way to do it | |
* */ | |
def printToFile(filename: String)(op: java.io.PrintWriter => Unit) { | |
val p = new java.io.PrintWriter(new java.io.BufferedWriter(new java.io.FileOutputStream(filename), "UTF-8")) | |
try op(p) finally p.close | |
} | |
// Example usage: | |
printToFile("filename")(p => { List("line1","line2","line3").foreach(p.println) }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment