vsingal5
vsingal5

Reputation: 304

PrintWriter in Scala not writing to file?

I have the following file creation/writing code:

val file =  new PrintWriter(new FileWriter(new File(TMP_DIR, fileName), true))
    file.write(getFirstRow(tableName))

For some weird reason, it's not writing to my file, but it creates it everytime. The getFirstRow method returns a string that I want to append to the file. What is going wrong?

Upvotes: 1

Views: 2124

Answers (1)

millhouse
millhouse

Reputation: 10007

You are neither flushing nor closeing the File (or the PrintWriter, which would also do that).

This is such a common mistake that it's a fantastic opportunity to use an example of the Loan Pattern:

def withPrintWriter(dir:String, name:String)(f: (PrintWriter) => Any) {
  val file = new File(dir, name)
  val writer = new FileWriter(file)
  val printWriter = new PrintWriter(writer)
  try {
    f(printWriter)
  }
  finally {
    printWriter.close()
  }

}

Which you use like this:

withPrintWriter("/tmp", "myFile") { printWriter =>
  printWriter.write("all good")
}

Upvotes: 6

Related Questions