[英]Groovy write to file (newline)
我創建了一個小函數,只是簡單地將文本寫入文件,但是我在將每條信息寫入新行時遇到問題。 有人能解釋為什么它把所有東西放在同一條線上嗎?
這是我的功能:
public void writeToFile(def directory, def fileName, def extension, def infoList) {
File file = new File("$directory/$fileName$extension")
infoList.each {
file << ("${it}\n")
}
}
我正在測試它的簡單代碼是這樣的:
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)
上面在該文件夾中創建了一個文本文件,文本文件的內容如下所示:
Today is a new dayTomorrow is the futureYesterday is the past
正如您所看到的,文本全部聚集在一起,而不是在每個文本的新行上分開。 我認為這與我如何將其添加到我的列表中有關?
正如@Steven指出的那樣,更好的方法是:
public void writeToFile(def directory, def fileName, def extension, def infoList) {
new File("$directory/$fileName$extension").withWriter { out ->
infoList.each {
out.println it
}
}
}
因為它為您處理行分隔符,並處理關閉編寫器
(並且每次編寫一行時都不會打開和關閉文件,原始版本可能會很慢)
它在我看來,就像你在windows中工作一樣,在這種情況下,一個新的行字符不僅僅是\\n
而是\\r\\n
例如,您始終可以通過System.getProperty("line.separator")
獲取正確的換行符。
可能更清潔使用PrintWriter及其方法:println只需確保在完成后關閉編寫器
我遇到了這個問題並受到其他貢獻者的啟發。 我需要每行向文件追加一些內容。 這就是我做的。
class Doh {
def ln = System.getProperty('line.separator')
File file //assume it's initialized
void append(String content) {
file << "$content$ln"
}
}
我覺得很漂亮:)
@Comment for ID:14。 這對我來說更容易寫:
out.append it
代替
out.println it
println在我的機器上只寫了ArrayList的第一個文件,並附加了我得到的整個List寫入文件。
無論如何,請快速和骯臟的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.