Groovy写入文件(换行符)

Sta*_*ovy 41 file-io groovy

我创建了一个小函数,只是简单地将文本写入文件,但是我在将每条信息写入新行时遇到问题.有人能解释为什么它把所有东西放在同一条线上吗?

这是我的功能:

public void writeToFile(def directory, def fileName, def extension, def infoList) {
    File file = new File("$directory/$fileName$extension")

    infoList.each {
        file << ("${it}\n")
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在测试它的简单代码是这样的:

def directory = 'C:/'
def folderName = 'testFolder'
def c

def txtFileInfo = []

String a = "Today is a new day"
String b = "Tomorrow is the future"
String d = "Yesterday is the past"

txtFileInfo << a
txtFileInfo << b
txtFileInfo << d

c = createFolder(directory, folderName) //this simply creates a folder to drop the txt file in

writeToFile(c, "garbage", ".txt", txtFileInfo)
Run Code Online (Sandbox Code Playgroud)

上面在该文件夹中创建了一个文本文件,文本文件的内容如下所示:

Today is a new dayTomorrow is the futureYesterday is the past
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,文本全部聚集在一起,而不是在每个文本的新行上分开.我认为这与我如何将其添加到我的列表中有关?

tim*_*tes 77

正如@Steven指出的那样,更好的方法是:

public void writeToFile(def directory, def fileName, def extension, def infoList) {
  new File("$directory/$fileName$extension").withWriter { out ->
    infoList.each {
      out.println it
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

因为它为您处理行分隔符,并处理关闭编写器

(并且每次编写一行时都不会打开和关闭文件,原始版本可能会很慢)


mfl*_*yan 30

在我看来,你是在为窗口工作在这种情况下,一个新行字符不是简单的\n而是\r\n

例如,您始终可以获得正确的换行符 System.getProperty("line.separator").


Ste*_*ven 8

可能更清洁使用PrintWriter及其方法:println只需确保在完成后关闭编写器


Pat*_*ick 7

我遇到了这个问题并受到其他贡献者的启发.我需要每行向文件追加一些内容.这就是我做的.

class Doh {
   def ln = System.getProperty('line.separator')
   File file //assume it's initialized 

   void append(String content) {
       file << "$content$ln"
   }
}
Run Code Online (Sandbox Code Playgroud)

我觉得很漂亮:)