方法1和方法2分別以下圖紅色和藍色高亮所示:app
其中第八行的雙引號包裹起來的變量表明GString,即JavaScript和ABAP裏的字符串模板。ide
代碼:3d
new File('c:\\temp', '1.txt').eachLine { line -> println line } new File('c:\\temp', '1.txt').eachLine { lineContent, lineNumber -> println "Line $lineNumber: $lineContent" }
方法3:若是想在依次讀取文件內容時增長對文件行讀取行爲的控制,能夠採用以下方法:code
def count = 0, MAXSIZE = 3
new File(baseDir,「haiku.txt」).withReader { reader ->
while (reader.readLine()) {
if (++count > MAXSIZE) {
throw new RuntimeException(‘Haiku should only have 3 verses’)
}
}
}blog
方法4:若是想將文件內容保存到一個list裏:ip
def list = new File('c:\\temp', '1.txt').collect {it} println list.size() list.each { println it};
方法5:對本地文件進行寫操做utf-8
寫入以前的文件原始內容:字符串
new File('c:\\temp','1.txt').withWriter('utf-8') { writer -> writer.writeLine '4 line' writer.writeLine '5 line' writer.writeLine '6 line' }
寫入後的文件:it
能夠看到寫入方式爲overwrite(複寫),而不是append(追加)io
要獲取更多Jerry的原創文章,請關注公衆號"汪子熙":