File Paths in Groovy

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

In Groovy, we can work with file paths using the java.nio.file.Path and java.nio.file.Paths classes. These classes provide methods to manipulate and query file paths in a way that is portable between operating systems.

import java.nio.file.Path
import java.nio.file.Paths

// Join should be used to construct paths in a portable way.
// It takes any number of arguments and constructs a hierarchical path from them.
def p = Paths.get("dir1", "dir2", "filename")
println "p: ${p}"

// You should always use Paths.get() instead of concatenating '/' or '\' manually.
// In addition to providing portability, it will also normalize paths by removing
// superfluous separators and directory changes.
println Paths.get("dir1//", "filename")
println Paths.get("dir1/../dir1", "filename")

// getParent() and getFileName() can be used to split a path to the
// directory and the file. There's no direct equivalent to Split in Groovy.
println "Parent(p): ${p.parent}"
println "FileName(p): ${p.fileName}"

// We can check whether a path is absolute.
println Paths.get("dir/file").isAbsolute()
println Paths.get("/dir/file").isAbsolute()

def filename = "config.json"

// Some file names have extensions following a dot. We can split the extension
// out of such names.
def ext = filename.tokenize('.').last()
println ext

// To find the file's name with the extension removed, use substring.
println filename.substring(0, filename.lastIndexOf('.'))

// relativize finds a relative path between a base and a target.
// It returns a Path that can be used to construct the target path
// relative to the base path.
def base = Paths.get("a/b")
def target = Paths.get("a/b/t/file")
def rel = base.relativize(target)
println rel

base = Paths.get("a/b")
target = Paths.get("a/c/t/file")
rel = base.relativize(target)
println rel

To run this Groovy script, save it to a file (e.g., file_paths.groovy) and execute it using the groovy command:

$ groovy file_paths.groovy
p: dir1\dir2\filename
dir1\filename
dir1\filename
Parent(p): dir1\dir2
FileName(p): filename
false
true
json
config
t\file
..\c\t\file

Note that the output may vary depending on the operating system. On Windows, you’ll see backslashes (\) as path separators, while on Unix-like systems, you’ll see forward slashes (/).

Groovy leverages Java’s NIO.2 API for file operations, which provides a more powerful and flexible way to work with files and directories compared to the older java.io.File class.