Reading Files in Groovy

Our first example demonstrates reading files in Groovy. Reading and writing files are basic tasks needed for many Groovy programs. Let’s look at some examples of reading files.

import groovy.transform.CompileStatic

@CompileStatic
class ReadingFiles {
    // This helper will streamline our error checks below.
    static void check(Exception e) {
        if (e != null) {
            throw e
        }
    }

    static void main(String[] args) {
        // Perhaps the most basic file reading task is
        // slurping a file's entire contents into memory.
        try {
            String dat = new File("/tmp/dat").text
            println(dat)
        } catch (Exception e) {
            check(e)
        }

        // You'll often want more control over how and what
        // parts of a file are read. For these tasks, start
        // by opening a file to obtain a FileInputStream.
        FileInputStream f
        try {
            f = new FileInputStream("/tmp/dat")

            // Read some bytes from the beginning of the file.
            // Allow up to 5 to be read but also note how many
            // actually were read.
            byte[] b1 = new byte[5]
            int n1 = f.read(b1)
            println("${n1} bytes: ${new String(b1, 0, n1)}")

            // You can also seek to a known location in the file
            // and read from there.
            long o2 = f.skip(1)
            byte[] b2 = new byte[2]
            int n2 = f.read(b2)
            println("${n2} bytes @ ${o2}: ${new String(b2, 0, n2)}")

            // The InputStream doesn't provide a built-in way to seek relative
            // to the current position or end of file, but you can implement
            // this functionality if needed.

            // There is no built-in rewind, but you can close and reopen the file
            f.close()
            f = new FileInputStream("/tmp/dat")

            // The BufferedReader class implements a buffered
            // reader that may be useful both for its efficiency
            // with many small reads and because of the additional
            // reading methods it provides.
            BufferedReader r4 = new BufferedReader(new InputStreamReader(f))
            char[] b4 = new char[5]
            r4.read(b4, 0, 5)
            println("5 bytes: ${new String(b4)}")

        } catch (Exception e) {
            check(e)
        } finally {
            // Close the file when you're done (usually this would
            // be scheduled immediately after opening with a try-with-resources).
            if (f != null) {
                f.close()
            }
        }
    }
}

To run the program:

$ echo "hello" > /tmp/dat
$ echo "groovy" >>   /tmp/dat
$ groovy ReadingFiles.groovy
hello
groovy
5 bytes: hello
2 bytes @ 6: gr
5 bytes: hello

This Groovy code demonstrates various ways to read files, including reading the entire file at once, reading specific portions, and using buffered readers. The code structure and explanations have been adapted to Groovy’s syntax and conventions while maintaining the overall flow of the original example.

Next, we’ll look at writing files.