Title here
Summary here
Here’s the translation of the Go code to Groovy, formatted in Markdown for Hugo:
Writing files in Groovy follows similar patterns to the ones we saw earlier for reading.
import groovy.io.FileType
def check(Exception e) {
if (e != null) {
throw e
}
}
// To start, here's how to dump a string (or just bytes) into a file.
def d1 = "hello\ngroovy\n"
try {
new File("/tmp/dat1").text = d1
} catch (Exception e) {
check(e)
}
// For more granular writes, open a file for writing.
def f = new File("/tmp/dat2")
f.createNewFile()
// It's idiomatic to use a try-with-resources block to ensure the file is closed
try (def writer = f.newWriter()) {
// You can write byte arrays as you'd expect.
def d2 = [115, 111, 109, 101, 10] as byte[]
def n2 = writer.write(new String(d2))
println "wrote ${n2} bytes"
// A write method for strings is also available.
def n3 = writer.write("writes\n")
println "wrote ${n3} bytes"
// Flush writes to ensure they're written to the file.
writer.flush()
// BufferedWriter provides buffered writers in addition to the buffered readers we saw earlier.
def bufferedWriter = new BufferedWriter(writer)
def n4 = bufferedWriter.write("buffered\n")
println "wrote ${n4} bytes"
// Use flush to ensure all buffered operations have been applied to the underlying writer.
bufferedWriter.flush()
}
Try running the file-writing code.
$ groovy writing-files.groovy
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes
Then check the contents of the written files.
$ cat /tmp/dat1
hello
groovy
$ cat /tmp/dat2
some
writes
buffered
Next we’ll look at applying some of the file I/O ideas we’ve just seen to the stdin
and stdout
streams.