檢查文件是否存在、可讀等等
File file = new File("out.txt")
println file.exists()
println file.canRead()
向文件寫入文本
File file = new File("out.txt")
file.write "First line\n"
file << "Second line\n"
file.append("hello\n")
println file.text
獲取文件全部內容
File file = new File('examples/data/count_digits.txt')
// 獲取文件全部內容
println file.getText('UTF-8')
println file.text
// 獲得文件的輸入流
def inputStream = file.newInputStream()
遍歷文件的全部行
File file = new File("/path/to/file")
// 第一種方法
def lines = file.readLines()
for (line in lines) {
// ...
}
// 第二種方法
file.eachLine { line, nb ->
println "Line $nb: $line"
}
時間屬性(修改時間、創建時間)
File file = new File("/path/to/file");
// 獲取文件修改時間
Long actualLastModified = file.lastModified();
// 設置文件修改時間
file.setLastModified(actualLastModified)
相關文章
「Apache Groovy」- 運行 Shell 命令
「Groovy」- 處理 Object 與 JSON String 之間的轉換
「Apache Groovy」- 連接 SQLite 數據庫
「Groovy」- 操作 HTML 文檔
「Groovy」- 彩色化輸出日志
參考文獻
Groovy: reading and writing files - appending content
Working with IO
How to read a file in Groovy into a string? - Stack Overflow
json - Groovy file check - Stack Overflow
Set last modified timestamp of a file using jimfs in Java - Stack Overflow
