我目前正在为一个函数编写测试,该函数采用文件路径并从中加载数据集。我无法更改该功能。目前为了测试它,我正在为测试函数的每次运行创建文件。我担心简单地创建文件然后删除它们是一种不好的做法。有没有更好的方法在 Scala 中创建临时测试文件?
import java.io.{File, PrintWriter}
val testFile = new File("src/main/resources/temp.txt" )
val pw = new PrintWriter(testFile)
val testLines = List("this is a text line", "this is the next text line")
testLines.foreach(pw.write)
pw.close
// test logic here
testFile.delete()
我通常更喜欢
java.nio
而不是java.io
。您可以像这样创建一个临时文件:
import java.nio.file.Files
Files.createTempFile()
您可以使用
Files.delete
将其删除。为了确保即使在出现错误的情况下也能删除文件,您应该将 delete
调用放入 finally
块中。