Groovy 写入文件(换行) [英] Groovy write to file (newline)
问题描述
我创建了一个简单的将文本写入文件的小函数,但是我在将每条信息写入新行时遇到了问题.有人可以解释为什么它把所有东西都放在同一条线上吗?
I created a small function that simply writes text to a file, but I am having issues making it write each piece of information to a new line. Can someone explain why it puts everything on the same line?
这是我的功能:
public void writeToFile(def directory, def fileName, def extension, def infoList) {
File file = new File("$directory/$fileName$extension")
infoList.each {
file << ("${it}
")
}
}
我用来测试它的简单代码是这样的:
The simple code I'm testing it with is something like this:
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)
上面在该文件夹中创建了一个文本文件,文本文件的内容如下所示:
The above creates a text file in that folder and the contents of the text file look like this:
Today is a new dayTomorrow is the futureYesterday is the past
如您所见,文本全部聚集在一起,而不是在每个文本的新行上分开.我认为这与我如何将其添加到我的列表中有关?
As you can see, the text is all bunched together instead of separated on a new line per text. I assume it has something to do with how I am adding it into my list?
推荐答案
在我看来,就像您在 Windows 中工作一样,在这种情况下,换行符不是简单的
而是
It looks to me, like you're working in windows in which case a new line character in not simply
but rather
例如,您始终可以通过 System.getProperty("line.separator")
获取正确的换行符.
You can always get the correct new line character through System.getProperty("line.separator")
for example.
这篇关于Groovy 写入文件(换行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!