Java Reference
In-Depth Information
The trim method is used in this example with the spread-dot operator to remove leading
and trailing spaces on each line. If your data is formatted in a specific way, the
splitEachLine method takes a delimiter and returns a list of the elements. For ex-
ample, if you have a data file that contains the following lines
1,2,3
a,b,c
then the data can be retrieved and parsed at the same time:
List dataLines = []
new File(" data.txt" ). splitEachLine (',') {
dataLines << it
}
assert dataLines == [['1','2','3'],['a','b','c']]
Writing to a file is just as easy:
File f = new File("$base /output.dat" )
f. write ('Hello, Groovy!')
assert f. text == 'Hello, Groovy!'
In Java, it's critical to close a file if you've written to it, because otherwise it may not flush
the buffer and your data may never make into the file. Groovy does that for you automatic-
ally.
Groovy also makes it easy to append to a file:
File temp = new File(" temp.txt" )
temp. write 'Groovy Kind of Love'
assert temp.readLines().size() == 1
temp.append "\nGroovin', on a Sunday afternoon..."
temp << "\nFeelin' Groovy"
assert temp.readLines().size() == 3
temp.delete()
The append method does what it sounds like, and the left-shift operator has been overrid-
den to do the same.
Several methods are available that iterate over files, like eachFile , eachDir , and even
eachFileRecurse . They each take closures that can filter what you want.
Search WWH ::




Custom Search