隐式追加方法无法正常工作

时间:2016-04-12 13:54:52

标签: scala

我正在尝试编写一个带有append方法的隐式append类。该方法应将String添加到文件末尾。

     def AppendToFile(file: File, str: String): Unit = {
    val append = new FileWriter(file)
    try 
      append.append(str).append("\n")  
    finally  
      append.close         
  }
  implicit class RichAppend(p: Path) {
      def append(fileName: String) = AppendToFile(p.toFile,fileName)
 }

然而,当我运行测试时出现错误。

  "[Second line
[info]   ]
[info]   " did not equal "[line_1
[info]   Second line]

这是我正在运行的测试:

test("Paths should have a .append method") {
    val pth = Paths.get("test.txt")
    val data = " line_1\nSecond"
    try {
    pth.append(pth,"line_1\n")
    pth.append(pth,"Second line\n")
     assert(new String(Files.readAllBytes(pth)) == "line_1\nSecond line\n")
    }
    finally {
      Files.deleteIfExists(pth)
     }
 }

1 个答案:

答案 0 :(得分:1)

文件编写器需要处于追加模式。 new FileWriter(file, true);

同样,append方法会以其当前编写的方式添加\n