File I/O with NIO

Demonstrates reading and writing files using Java NIO with Path, Files, and BufferedReader, including proper resource management and exception handling.

JavaConfig Management

Code

snippet
import java.io.IOException;
import java.nio.file.*;
import java.util.List;
import java.util.stream.Stream;

public class FileReadWrite {

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

        Files.createDirectories(dir);

        List<String> lines = List.of(
            "First line",
            "Second line",
            "Third line"
        );
        Files.write(file, lines, StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING);

        System.out.println("File size: " + Files.size(file) + " bytes");

        try (Stream<String> fileLines = Files.lines(file)) {
            fileLines.map(String::toUpperCase)
                .forEach(System.out::println);
        }

        String content = Files.readString(file);
        System.out.println("Total chars: " + content.length());

        Files.deleteIfExists(file);
        System.out.println("File deleted: " + !Files.exists(file));
    }
}

What the code does

The working surface is the class FileReadWrite — everything else is wiring.

try-with-resources closes each declared resource automatically on every exit path.

Applying it

Running the file prints labeled results such as File size:, Total chars:, File deleted: — each operation’s effect is visible in the output.

Statements that matter

fileLines.map(String::toUpperCase)
    .forEach(System.out::println);

Interactive Tools for This Topic

FAQ

What does File I/O with NIO print when run?
Running the file directly is enough — expect labeled output lines such as `File size:`, `Total chars:`, `File deleted:`.