bhylu.com

Advertisements

Java Create a Text File Without Overwriting a Stranger’s Data

Writing text is a state-changing operation. Decide whether an existing file should cause failure, be replaced or be appended to instead of accepting a default accidentally.

Understand the idea

Files.writeString supports a chosen charset and open options. CREATE_NEW fails if the file already exists, making it useful when silently replacing data would be wrong. A safe learning example creates a uniquely named directory and keeps every file operation inside it. This example’s cleanup removes only paths it created; it is not a recursive deletion recipe.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

import java.nio.file.*;
import java.nio.charset.StandardCharsets;

public class Main {
    public static void main(String[] args) throws Exception {
        Path folder = Files.createTempDirectory("bhylu-write-");
        Path file = folder.resolve("sessions.txt");
        try {
            Files.writeString(file, "Clay\nWood\n", StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW);
            System.out.println(Files.readAllLines(file, StandardCharsets.UTF_8).size());
        } finally {
            Files.deleteIfExists(file);
            Files.delete(folder);
        }
    }
}

Expected output

2

The output file contains two text lines encoded as UTF-8. CREATE_NEW documents that this operation creates rather than replaces a file. Reading the lines checks the actual stored result before cleanup. A real application may need atomic replacement and a durability policy; simply writing a file is not a transaction guarantee across crashes.

Check the official Java documentation for detailed contracts and supported options.