Skip to content

Instantly share code, notes, and snippets.

@xhoong
Created January 17, 2017 01:11
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 xhoong/b2912a27cbff5b9cde603a2612917ee6 to your computer and use it in GitHub Desktop.
Save xhoong/b2912a27cbff5b9cde603a2612917ee6 to your computer and use it in GitHub Desktop.
Functional output stream
/**
* Used for reading/writing to database, files, etc.
* Code From the book "Beginning Scala"
* http://www.amazon.com/Beginning-Scala-David-Pollak/dp/1430219890
* http://stackoverflow.com/a/5218279
*/
def using[A <: {def close(): Unit}, B](param: A)(f: A => B): B =
try { f(param) } finally { param.close() }
def writeToFile(fileName:String, data:String) =
using (new FileWriter(fileName)) {
fileWriter => fileWriter.write(data)
}
def appendToFile(fileName:String, textData:String) =
using (new FileWriter(fileName, true)){
fileWriter => using (new PrintWriter(fileWriter)) {
printWriter => printWriter.println(textData)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment