Directories in Java
Here’s the translation of the Go code example to Java, along with explanations in Markdown format suitable for Hugo:
Java has several useful classes for working with directories in the file system.
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(IOException 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();
if (!created) {
System.out.println("Failed to create directory");
return;
}
// When creating temporary directories, it's good practice to delete them when done.
// We'll use a try-with-resources to ensure cleanup.
try {
// Helper method to create a new empty file.
createEmptyFile("subdir/file1");
// We can create a hierarchy of directories, including parents with mkdirs().
// This is similar to the command-line `mkdir -p`.
File parentChild = new File("subdir/parent/child");
parentChild.mkdirs();
createEmptyFile("subdir/parent/file2");
createEmptyFile("subdir/parent/file3");
createEmptyFile("subdir/parent/child/file4");
// listFiles() lists directory contents, returning an array of File objects.
File parentDir = new File("subdir/parent");
File[] contents = parentDir.listFiles();
System.out.println("Listing subdir/parent");
if (contents != null) {
for (File entry : contents) {
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(".");
contents = currentDir.listFiles();
System.out.println("Listing subdir/parent/child");
if (contents != null) {
for (File entry : contents) {
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.
// Files.walk() returns a Stream of Path objects that we can iterate over.
System.out.println("Visiting subdir");
Files.walk(Paths.get("subdir"))
.forEach(path -> visit(path.toString(), Files.isDirectory(path)));
} catch (IOException e) {
e.printStackTrace();
} finally {
// Clean up: delete the temporary directory 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 visit(String path, boolean isDirectory) {
System.out.println(" " + path + " " + isDirectory);
}
private static void deleteDirectory(File dir) {
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
deleteDirectory(file);
} else {
file.delete();
}
}
}
dir.delete();
}
}To run the program, compile it and use java:
$ javac Directories.java
$ java Directories
Listing subdir/parent
child true
file2 false
file3 false
Listing subdir/parent/child
file4 false
Visiting subdir
subdir true
subdir/file1 false
subdir/parent true
subdir/parent/child true
subdir/parent/child/file4 false
subdir/parent/file2 false
subdir/parent/file3 falseThis Java program demonstrates various operations with directories, including creating directories, listing contents, changing the working directory, and recursively walking through a directory structure. It uses classes from the java.io and java.nio.file packages to handle file system operations.
The program creates a temporary directory structure, performs operations on it, and then cleans up by deleting the created directories and files. It showcases the use of File class methods like mkdir(), mkdirs(), and listFiles(), as well as newer APIs like Files.walk() for recursive directory traversal.
Note that Java doesn’t have a direct equivalent to Go’s defer keyword, so we use a try-with-resources statement to ensure cleanup of resources. Also, changing the current working directory is generally not recommended in Java applications, but it’s demonstrated here using System.setProperty("user.dir", ...) for completeness.