更改文件的内容不会更改lastModified文件

时间:2017-05-08 01:04:12

标签: java scala file

我正在编写一个简单的测试来更改File的内容。正如您所看到的,印刷内容是预期的。但lastModified()描述符未被修改。最后,我想要的是一个Boolean字段,表示我的文件是否已更改。

我需要让我的线程睡眠1秒才能通过测试...我不喜欢这样它不可靠。

我得到的错误:

[header1,header2, before,before]
[header1,header2, after,after]

false was not equal to true
ScalaTestFailureLocation: NonSense at (NonSense.scala:38)
Expected :true
Actual   :false

以下代码段:

import java.io.File
import java.nio.file.{Files, Path, Paths}

import org.apache.commons.io.FileUtils
import org.scalatest.{FlatSpec, Matchers}

class NonSense extends FlatSpec with Matchers {

  val classLoader: ClassLoader = getClass.getClassLoader
  val testAclsPath: Path = Paths.get(classLoader.getResource("file/test.csv").getPath)

  def withTempConfigFile(block: (Path) => Unit) {
    val tempDir: Path = Files.createTempDirectory("test")
    val tempCsv = new File(tempDir.toFile, "test.csv")
    val path = tempCsv.toPath.toAbsolutePath
    Files.copy(testAclsPath, path)
    block(path)
  }


  "changing a file" should "change last modified timestamp" in {
    withTempConfigFile { (path) =>
        // refresh and get current Acls
        val lastModified = path.toFile.lastModified
        // read CSV
        val file = path.toFile
        val lines = FileUtils.readLines(file, "UTF-8")
        System.out.println(lines)
        // delete the last line
        val deletedLine = lines.remove(lines.size() - 1)
        // add a line
        lines.add("after,after")
        // write to file
        // Thread.sleep(10) doesn't change anything, but Thread.sleep(1000) does
        FileUtils.writeLines(path.toFile, "UTF-8", lines, false)
        val linesChanged = FileUtils.readLines(file, "UTF-8")
        System.out.println(linesChanged)
        // assert the obvious - not working
        path.toFile.lastModified() > lastModified shouldBe true
      }
  }

}

0 个答案:

没有答案