SyntaxStudy
Sign Up
Java Writing Files and Path Operations
Java Beginner 1 min read

Writing Files and Path Operations

Writing files with the NIO.2 API is symmetrical to reading. Files.writeString() writes a String to a file, while Files.write() writes a list of bytes or lines. By default these methods create the file if it does not exist and truncate it if it does. You can control this behaviour with StandardOpenOption values: APPEND adds to the end of an existing file, CREATE_NEW fails if the file already exists, and TRUNCATE_EXISTING (the default) overwrites. For writing large amounts of data efficiently, BufferedWriter wraps an underlying Writer and buffers output. You get one from Files.newBufferedWriter(path, charset, options). The write() method writes a string and newLine() writes the platform-appropriate line separator. Always use try-with-resources to ensure the writer is flushed and closed — data in the buffer is lost if the writer is not properly closed. The Path interface and its companion Files class offer a comprehensive set of operations for managing the file system: Files.exists(), Files.createDirectories(), Files.copy(), Files.move(), Files.delete(), Files.size(), and Files.getLastModifiedTime(). Path is also an improvement over the old java.io.File because it is immutable and its methods throw IOException instead of silently returning false.
Example
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.List;

public class WritingFilesDemo {

    public static void main(String[] args) throws IOException {
        Path dir  = Path.of("output");
        Path file = dir.resolve("report.txt");

        // Create directory tree
        Files.createDirectories(dir);

        // --- Files.writeString (simple) ---
        Files.writeString(file, "=== Report ===\n", StandardCharsets.UTF_8);

        // --- Append with StandardOpenOption.APPEND ---
        Files.writeString(file, "Item 1: done\n",
            StandardCharsets.UTF_8, StandardOpenOption.APPEND);

        // --- Files.write with list of lines ---
        List<String> lines = List.of("Item 2: done", "Item 3: pending", "");
        Files.write(file, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);

        // --- BufferedWriter for large output ---
        Path bigFile = dir.resolve("big.txt");
        try (BufferedWriter writer =
                Files.newBufferedWriter(bigFile, StandardCharsets.UTF_8)) {
            for (int i = 1; i <= 5; i++) {
                writer.write("Record " + i + ": value=" + (i * 10));
                writer.newLine();
            }
        } // flush + close happens here

        // Read back to verify
        System.out.println("report.txt:");
        Files.readAllLines(file).forEach(l -> System.out.println("  " + l));

        // --- Path operations ---
        System.out.println("\nbig.txt size: " + Files.size(bigFile) + " bytes");
        System.out.println("Exists:       " + Files.exists(file));

        // Cleanup
        Files.delete(bigFile);
        Files.delete(file);
        Files.delete(dir);
    }
}