Embed Directive in Groovy

Here’s the translation of the Go code to Groovy, formatted in Markdown suitable for Hugo:

Our first program demonstrates embedding files and folders into the binary at build time. Here’s the full source code:

import groovy.io.FileType

// In Groovy, we don't have an exact equivalent of Go's embed directive.
// Instead, we can use Groovy's built-in file handling capabilities.

class EmbedExample {
    // Read the contents of a single file
    static String fileString = new File('folder/single_file.txt').text

    // Read the contents of a file as bytes
    static byte[] fileByte = new File('folder/single_file.txt').bytes

    // Create a map to simulate embedding multiple files
    static Map<String, String> folder = [:]

    static {
        // Simulate embedding multiple files
        new File('folder').eachFileMatch(FileType.FILES, ~/.*\.hash/) { file ->
            folder[file.name] = file.text
        }
    }

    static void main(String[] args) {
        // Print out the contents of 'single_file.txt'
        println(fileString)
        println(new String(fileByte))

        // Retrieve some files from the simulated embedded folder
        println(folder['file1.hash'])
        println(folder['file2.hash'])
    }
}

In Groovy, we don’t have a direct equivalent of the //go:embed directive. Instead, we use Groovy’s built-in file handling capabilities to achieve similar functionality.

We use File operations to read the contents of single files, both as a string and as bytes. To simulate embedding multiple files, we use a Map and populate it with file contents at runtime.

Use these commands to set up the example files:

$ mkdir -p folder
$ echo "hello groovy" > folder/single_file.txt
$ echo "123" > folder/file1.hash
$ echo "456" > folder/file2.hash

Then run the Groovy script:

$ groovy EmbedExample.groovy
hello groovy
hello groovy
123
456

This example demonstrates how to work with file contents in Groovy, which can be used as an alternative to embedding files at compile time.