Groovy — Reading UTF-8 files with eachLine
Groovy eachLine can read a text file line by line with a specified encoding. A finally block can remove the temporary file even if processing fails.
A simple example
Read back one letter
- Start with A
- Do this Write, then read
- Result A
def file = File.createTempFile("letter", ".txt")
try {
file.text = "A"
println(file.text)
} finally {
file.delete()
}
A
Sum two lines from a temporary report
The JDK creates a private temporary path. eachLine reads text with the requested character encoding. The finally block removes the file on both normal and exceptional exits.
Morning staff record four returns in a file and afternoon staff record seven on the next line. Read each line as a number and add it to the running total. The day ends with eleven returns.
Run the example
Groovy 4 on the JVM. Run these commands from the directory containing the example.
groovy Lesson.groovy
import java.nio.file.Files
def path = Files.createTempFile('readings', '.txt')
try {
Files.write(path, ['4', '7'])
int total = 0
path.toFile().eachLine('UTF-8') { line ->
if (line.trim()) total += line.trim().toInteger()
}
println total
} finally {
Files.deleteIfExists(path)
}
11
The file contains two whole-number readings on separate lines. Reading from the beginning gives 4 and 7, for a total of 11. The example creates its own file, so it can run in a clean working directory.
Try it yourself
Add a third line containing 12.
Check your answer
The new total is 23. This report format assumes valid integer readings. When accepting external input, apply the validation techniques from the preceding lesson.