Skillversitas

File Input/Output

Java provides several APIs for file operations: java.nio.file (modern, recommended since Java 7), java.io (legacy, still relevant for streams), and the Files utility class for simple operations. The NIO.2 API (Path, Files) is more compact and powerful than traditional IO.

Files.readAllLines() and Files.readString() (Java 11+) make it easy to read an entire file. Files.write() writes to a file easily. For large files, use BufferedReader/BufferedWriter or Files.lines() to stream line by line without loading the whole file into memory.

Path represents the location of a file/directory in the file system. It supports relative and absolute path operations, as well as cross-platform path construction using Path.of() or Paths.get().

Java File APIs:

API Main Classes Use
NIO.2 Path, Files Modern file operations (recommended)
IO FileReader, BufferedReader Stream-based I/O
NIO FileChannel High-performance I/O

Code Example

import java.nio.file.*;
import java.io.IOException;
import java.util.List;

public class FileIO {
    public static void main(String[] args) {
        try {
            // Create a path
            Path path = Path.of("data", "example.txt");
            Path parent = path.getParent();

            // Write a file (Java 11+)
            Files.writeString(path, "Hello, World!\nThis is the second line.\n");

            // Read the entire file
            String content = Files.readString(path);
            System.out.println("=== File Contents ===");
            System.out.println(content);

            // Read line by line
            List<String> lines = Files.readAllLines(path);
            for (int i = 0; i < lines.size(); i++) {
                System.out.println((i + 1) + ": " + lines.get(i));
            }

            // File info
            System.out.println("\nSize: " + Files.size(path) + " bytes");
            System.out.println("Exists: " + Files.exists(path));
            System.out.println("Is directory: " + Files.isDirectory(parent));

            // Append
            Files.writeString(path, "Third line appended.\n",
                StandardOpenOption.APPEND);

            // Delete the file
            Files.delete(path);
            System.out.println("File deleted.");

        } catch (IOException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

Code Explanation

  1. Path.of("data", "example.txt") creates a Path object — it accepts multiple arguments or a single path string.
  2. Files.writeString(path, text) writes a string to a file (Java 11+). It automatically overwrites the file if it already exists.
  3. Files.readString(path) reads the entire file contents as a String.
  4. Files.readAllLines(path) returns a List<String> — each line is one element.
  5. StandardOpenOption.APPEND modifies writeString to append to the end of the file without overwriting.
  6. All file operations are wrapped in a try-catch for IOException, because I/O operations can fail.

Everyday Example

A daily shopping logger program that stores data in a file:

import java.nio.file.*;
import java.io.IOException;
import java.time.LocalDate;
import java.util.Scanner;

public class CatatanBelanja {
    static final Path FILE = Path.of("belanja.txt");

    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);

        System.out.print("Item name: ");
        String item = sc.nextLine();
        System.out.print("Price: ");
        double price = sc.nextDouble();

        String catatan = LocalDate.now() + " | " + item + " | $"
            + String.format("%,.0f", price) + "\n";

        Files.writeString(FILE, catatan, StandardOpenOption.APPEND);
        System.out.println("Recorded: " + catatan.trim());

        // Display all records
        if (Files.exists(FILE)) {
            System.out.println("\n=== All Records ===");
            List<String> lines = Files.readAllLines(FILE);
            for (String b : lines) {
                System.out.println(b);
            }
        }
    }
}

Summary

The java.nio.file API is the modern standard for file I/O in Java. Files.writeString() and Files.readString() (Java 11+) make simple file operations very compact. For large files, consider streaming with Files.lines() or BufferedReader for memory efficiency.