Search⌘ K
AI Features

Solution: Simple Config Creator

Explore how to create and manage configuration files in Java using NIO. Understand key methods like Files.writeString and Path.of, handle checked IOExceptions properly, and implement logic to create or load config files efficiently.

We'll cover the following...
Java 25
import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;
public class ConfigLoader {
public static void ensureConfigExists(String fileName) throws IOException {
// Convert String to Path
Path path = Path.of(fileName);
// Check if file exists
boolean exists = Files.exists(path);
if (!exists) {
// Define default content using a Text Block
String defaults = """
host=localhost
port=8080
debug=true
""";
// Write the defaults to the file
Files.writeString(path, defaults);
System.out.println("Status: Config created.");
} else {
System.out.println("Status: Config loaded.");
}
}
public static void main(String[] args) {
try {
String fileName = "app.config";
// Test 1: File does not exist
System.out.println("--- Test 1: Initial Check ---");
ensureConfigExists(fileName);
// Test 2: File now exists (calling the method again)
System.out.println("\n--- Test 2: Re-check ---");
ensureConfigExists(fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}
...