File Paths in Logo

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

The java.nio.file.Paths class provides methods to work with file paths in a way that is portable between operating systems. For example, dir/file on Linux vs. dir\file on Windows.

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

public class FilePaths {
    public static void main(String[] args) {
        // Paths.get() should be used to construct paths in a portable way.
        // It takes any number of arguments and constructs a hierarchical path from them.
        Path p = Paths.get("dir1", "dir2", "filename");
        System.out.println("p: " + p);

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

        // getParent() and getFileName() can be used to split a path to the
        // directory and the file.
        System.out.println("p.getParent(): " + p.getParent());
        System.out.println("p.getFileName(): " + p.getFileName());

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

        String filename = "config.json";

        // Some file names have extensions following a dot. We can get
        // the extension using getExtension() from Apache Commons IO library.
        String ext = org.apache.commons.io.FilenameUtils.getExtension(filename);
        System.out.println(ext);

        // To find the file's name with the extension removed,
        // use getBaseName() from Apache Commons IO library.
        System.out.println(org.apache.commons.io.FilenameUtils.getBaseName(filename));

        // relativize() finds a relative path between a base and a target.
        // It returns a Path that represents the relative path.
        Path base = Paths.get("a/b");
        Path target = Paths.get("a/b/t/file");
        Path rel = base.relativize(target);
        System.out.println(rel);

        target = Paths.get("a/c/t/file");
        rel = base.relativize(target);
        System.out.println(rel);
    }
}

To run this program, you would need to include the Apache Commons IO library in your classpath. You can download it from the Apache Commons website or include it in your project using a build tool like Maven or Gradle.

The output of this program would be similar to:

p: dir1\dir2\filename
dir1\filename
dir1\filename
p.getParent(): dir1\dir2
p.getFileName(): filename
false
true
json
config
t\file
..\c\t\file

Note that the actual output may vary depending on your operating system, as the path separator could be different.