// files.groovy — reading and writing files the Groovy way. def dir = File.createTempDir() def csv = new File(dir, 'orders.csv') // Write: text in one go csv.text = '''id,customer,total PO-1,Acme,250 PO-2,Globex,90 PO-3,Acme,1200 ''' // Append csv << 'PO-4,Initech,40\n' // Read all lines def lines = csv.readLines() println "${lines.size() - 1} data rows" // 4 data rows // Read line by line (memory-friendly for big files), skipping the header def total = 0 csv.eachLine { line, number -> if (number == 1) return // header def (id, customer, amount) = line.split(',') total += amount.toInteger() } println "Total: $total" // 1580 // Parse into maps using the header def header = lines.head().split(',') def rows = lines.tail().collect { l -> [header, l.split(',')].transpose().collectEntries() } println rows.findAll { it.customer == 'Acme' }*.id // [PO-1, PO-3] // Write with a writer (closes automatically) def report = new File(dir, 'report.txt') report.withWriter('UTF-8') { w -> rows.groupBy { it.customer }.each { cust, list -> w.writeLine("$cust: ${list.size()} order(s)") } } print report.text // List and clean up files dir.eachFile { println "file: ${it.name} (${it.length()} bytes)" } dir.deleteDir() println "cleaned up: ${!dir.exists()}"