我有以下文件创建/编写代码:
val file = new PrintWriter(new FileWriter(new File(TMP_DIR, fileName), true))
file.write(getFirstRow(tableName))
出于某种奇怪的原因,它没有写入我的文件,而是每次都创建它。getFirstRow 方法返回一个我想附加到文件的字符串。出了什么问题?
您既不是flush
ing 也不是close
ing the File
(或 the PrintWriter
,它也会这样做)。
这是一个非常常见的错误,这是使用贷款模式示例的绝佳机会:
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()
}
}
你像这样使用它:
withPrintWriter("/tmp", "myFile") { printWriter =>
printWriter.write("all good")
}