Files and eachLine

The GDK adds methods to java.io.File: text reads the whole file, an assignment writes it, and a closure walks it a line at a time without loading the rest.

Write, append and read

notes.groovy

def file = new File('notes.txt') file.text = 'first line\nsecond line\n' file << 'third line\n' file.append('fourth line\n') println file.exists() println file.size() > 0 println file.readLines() println file.text.split('\n').length

groovy notes.groovy

true
true
[first line, second line, third line, fourth line]
4

text = replaces the file, << appends, and readLines() returns the lines without their terminators. Each call opens and closes the file, which is fine for a small one and wrong for a loop.

Line by line

lines.groovy

def file = new File('log.txt') file.text = 'INFO start\nWARN disk\nERROR stop\n' file.eachLine { String line, int number -> println "${number}: ${line}" } def errors = file.filterLine { String line -> line.startsWith('ERROR') } println errors.toString().trim() file.withWriterAppend { writer -> writer.write('INFO done\n') } println file.readLines().size()

groovy lines.groovy

1: INFO start
2: WARN disk
3: ERROR stop
ERROR stop
4

eachLine passes the line and its number, and filterLine writes the matching lines into a writer, which the example prints. withWriterAppend gives a writer that is closed when the closure returns, also when it throws.

A folder

folder.groovy

def folder = new File('data') folder.mkdirs() new File(folder, 'b.txt').text = 'b' new File(folder, 'a.txt').text = 'a' new File(folder, 'c.txt').text = 'c' println folder.directory println folder.listFiles().sort { File file -> file.name }*.name println folder.list().sort() folder.eachFile { File file -> println "${file.name}: ${file.text}" }

groovy folder.groovy

true
[a.txt, b.txt, c.txt]
[a.txt, b.txt, c.txt]
c.txt: c
a.txt: a
b.txt: b

listFiles() returns an array in the order of the file system, so the example sorts it before printing: an unsorted folder listing is the classic output that changes between machines. eachFile visits the same entries and gives the closure a File.

Related

Автор статьи: Arthur Isaev