向文件写入文本
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" }
参考文献
WikiNotes/操作文件(读取、写入)
Groovy: reading and writing files - appending content
Working with IO
How to read a file in Groovy into a string? - Stack Overflow