Directories in Mercury

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

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Directories {
    public static void main(String[] args) throws IOException {
        // Create a new sub-directory in the current working directory.
        Files.createDirectory(Paths.get("subdir"));

        // When creating temporary directories, it's good practice to
        // delete them when we're done. We'll use a try-with-resources
        // block to ensure cleanup.
        try {
            // Helper function to create a new empty file.
            createEmptyFile("subdir/file1");

            // We can create a hierarchy of directories, including
            // parents with createDirectories. This is similar to the
            // command-line `mkdir -p`.
            Files.createDirectories(Paths.get("subdir/parent/child"));

            createEmptyFile("subdir/parent/file2");
            createEmptyFile("subdir/parent/file3");
            createEmptyFile("subdir/parent/child/file4");

            // list directory contents
            System.out.println("Listing subdir/parent");
            Files.list(Paths.get("subdir/parent")).forEach(path -> {
                System.out.println(" " + path.getFileName() + " " + Files.isDirectory(path));
            });

            // Change the current working directory
            System.setProperty("user.dir", "subdir/parent/child");

            // Now we'll see the contents of subdir/parent/child
            // when listing the current directory.
            System.out.println("Listing current directory");
            Files.list(Paths.get(".")).forEach(path -> {
                System.out.println(" " + path.getFileName() + " " + Files.isDirectory(path));
            });

            // Change back to where we started
            System.setProperty("user.dir", "../../..");

            // We can also visit a directory recursively,
            // including all its sub-directories. Files.walkFileTree
            // accepts a FileVisitor to handle every file or
            // directory visited.
            System.out.println("Visiting subdir");
            Files.walkFileTree(Paths.get("subdir"), new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    System.out.println(" " + file + " " + Files.isDirectory(file));
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                    System.out.println(" " + dir + " " + Files.isDirectory(dir));
                    return FileVisitResult.CONTINUE;
                }
            });

        } finally {
            // Clean up: delete the subdir and all its contents
            deleteDirectory(new File("subdir"));
        }
    }

    private static void createEmptyFile(String name) throws IOException {
        Files.write(Paths.get(name), new byte[0]);
    }

    private static void deleteDirectory(File directory) {
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    deleteDirectory(file);
                } else {
                    file.delete();
                }
            }
        }
        directory.delete();
    }
}

This Java program demonstrates various operations for working with directories:

  1. We start by creating a new subdirectory using Files.createDirectory().

  2. We use a helper method createEmptyFile() to create empty files.

  3. Files.createDirectories() is used to create a hierarchy of directories, similar to mkdir -p in Unix.

  4. We list directory contents using Files.list() and print each entry.

  5. To change the current working directory, we use System.setProperty("user.dir", ...). Note that this is not recommended in production code and is used here for demonstration purposes only.

  6. We demonstrate recursive directory traversal using Files.walkFileTree() with a SimpleFileVisitor.

  7. Finally, we clean up by deleting the created directory and all its contents using a recursive deleteDirectory() method.

To run this program:

$ javac Directories.java
$ java Directories

This will create the directory structure, list its contents, and then clean up by removing all created files and directories.

Note: Java’s file I/O operations can throw IOException, which we’re declaring in the method signature. In a real-world application, you’d want to handle these exceptions more gracefully.