Directories in Fortress

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

Our first program will demonstrate working with directories in the file system. Here’s the full source code:

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 {
    
    private static void check(Exception e) {
        if (e != null) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        // Create a new sub-directory in the current working directory.
        File subdir = new File("subdir");
        boolean created = subdir.mkdir();
        check(created ? null : new IOException("Failed to create directory"));

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

            // We can create a hierarchy of directories, including parents.
            // This is similar to the command-line `mkdir -p`.
            File parentChild = new File("subdir/parent/child");
            created = parentChild.mkdirs();
            check(created ? null : new IOException("Failed to create directories"));

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

            // list directory contents
            File parentDir = new File("subdir/parent");
            System.out.println("Listing subdir/parent");
            for (File entry : parentDir.listFiles()) {
                System.out.println(" " + entry.getName() + " " + entry.isDirectory());
            }

            // 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.
            File currentDir = new File(".");
            System.out.println("Listing subdir/parent/child");
            for (File entry : currentDir.listFiles()) {
                System.out.println(" " + entry.getName() + " " + entry.isDirectory());
            }

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

            // We can also visit a directory recursively, including all its sub-directories.
            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 by deleting the subdir and all its contents
            deleteDirectory(subdir);
        }
    }

    private static void createEmptyFile(String name) throws IOException {
        File file = new File(name);
        file.createNewFile();
    }

    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 program demonstrates various operations with directories:

  1. We create a new subdirectory using mkdir().
  2. We use a helper method to create empty files.
  3. We create a hierarchy of directories using mkdirs().
  4. We list directory contents using listFiles().
  5. We change the current working directory using System.setProperty("user.dir", ...).
  6. We recursively visit all files and directories using Files.walkFileTree().

To run this program, save it as Directories.java, compile it with javac Directories.java, and then run it with java Directories.

Note that Java’s file operations are more verbose than Go’s, and error handling is done through exceptions rather than returned error values. Also, Java doesn’t have a direct equivalent to Go’s defer, so we use a try-finally block to ensure cleanup.

The output will be similar to the Go version, showing the created directory structure and the results of listing and walking the directories.