Search⌘ K
AI Features

Solution: Simple Config Creator

Explore how to create a simple configuration file in Java using NIO.2, including file existence checks and writing default content safely. Understand exception handling with IOException and how to confirm file creation or loading status.

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();
}
}
}
...