Skip to content

Instantly share code, notes, and snippets.

@malcolmgreaves
Last active August 26, 2019 15:40
Show Gist options
  • Save malcolmgreaves/47a1ac470cd60cffe72ddcf1ea7b7df0 to your computer and use it in GitHub Desktop.
Save malcolmgreaves/47a1ac470cd60cffe72ddcf1ea7b7df0 to your computer and use it in GitHub Desktop.
Write a string to a temporary file in Scala.
import java.io.{ File, PrintWriter }
/** Creates a temporary file, writes the input string to the file, and the file handle.
*
* NOTE: This funciton uses the createTempFile function from the File class. The prefix and
* suffix must be at least 3 characters long, otherwise this function throws an
* IllegalArgumentException.
*/
def writeToTempFile(contents: String,
prefix: Option[String] = None,
suffix: Option[String] = None): File = {
val tempFi = File.createTempFile(prefix.getOrElse("prefix-"),
suffix.getOrElse("-suffix"))
tempFi.deleteOnExit()
new PrintWriter(tempFi) {
// Any statements inside the body of a class in scala are executed on construction.
// Therefore, the following try-finally block is executed immediately as we're creating
// a standard PrinterWriter (with its implementation) and then using it.
// Alternatively, we could have created the PrintWriter, assigned it a name,
// then called .write() and .close() on it. Here, we're simply opting for a terser representation.
try {
write(contents)
} finally {
close()
}
}
tempFi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment