Reading — step 1 of 5
Learn
~2 min readStrings, Regex, I/O
Groovy makes file I/O concise.
Reading a file
def file = new File("data.txt")
file.text // entire content as String
file.bytes // entire content as byte[]
file.readLines() // List<String>
file.eachLine { line, num ->
println "$num: $line"
}
Writing
new File("out.txt").text = "hello\n" // overwrite
new File("log.txt") << "appended\n" // append
new File("data.bin").bytes = someByteArray
The << operator on a File appends — concise but mind the encoding.
Stream-style for big files
new File("big.csv").withReader { reader ->
def line
while ((line = reader.readLine()) != null) {
process(line)
}
}
withReader ensures the reader is closed after the block — idiomatic resource management.
Walking a directory
new File("src").eachFileRecurse { f ->
if (f.name.endsWith(".groovy")) {
println f.absolutePath
}
}
new File("src").eachFile { f ->
println f.name // direct children only
}
stdin / stdout
For scripts (which is most Groovy code):
System.in.eachLine { line ->
println line.toUpperCase()
}
// Or read all at once:
def text = System.in.text
// Or single line:
def line = System.in.newReader().readLine()
printf / println
println "hello" // line + newline
print "no newline"
printf("%-10s %d\n", "hi", 42) // C-style
println "item: " + value
File system queries
def f = new File("data.txt")
f.exists()
f.size() // bytes
f.canRead()
f.canWrite()
f.isDirectory()
f.isFile()
f.lastModified() // ms since epoch
Process execution
def proc = "git status".execute()
proc.waitForOrKill(5000)
println proc.text // stdout
println proc.errStr // stderr
println proc.exitValue() // 0/non-zero
// Pipe-like:
def out = ("ls -la" | "grep .groovy").text
Configurable I/O
file.withReader("UTF-8") { ... } // explicit encoding
file.append("more\n", "UTF-8")
file.write("new content", "UTF-16")
For scripts that aren't files-on-disk (like Judge0), most of this is conceptual — but the same idioms apply when you have a real filesystem.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…