Scala中的PrintWriter没有写入文件? [英] PrintWriter in Scala not writing to file?
问题描述
val file = new PrintWriter(new FileWriter(new File(TMP_DIR ,fileName),true))
file.write(getFirstRow(tableName))
一些奇怪的原因,它不是写给我的文件,而是每次创建它。 getFirstRow方法返回一个我想追加到文件的字符串。出了什么问题? 您不是 flush 关闭
文件
(或者 PrintWriter
,也可以这样做) / p>
这是一个常见的错误,使用贷款模式:
$ b $ pre $ def $ withPrintWriter(dir:String,name:String)(f: (PrintWriter)=> Any){
val file = new File(dir,name)
val writer = new FileWriter(file)$ b $ val printWriter = new PrintWriter(writer)
试试{
f(printWriter)
}
finally {
printWriter.close()
}
$ p
$ p
$ b $ pre> withPrintWriter(/ tmp,myFile){printWriter =>
printWriter.write(all good)
}
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?
You are neither flush
ing nor close
ing 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")
}
这篇关于Scala中的PrintWriter没有写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!