File Input/Output in Java

Site Admin · 11 Sep 2026 · 10 views

Reading and Writing Text Files

Text I/O is the most common file task. Modern Java offers Files and BufferedReader for clean, readable code.

Reading a File

import java.nio.file.*;

// Read all lines at once
List<String> lines = Files.readAllLines(Path.of("notes.txt"));

// Stream a large file line by line
Files.lines(Path.of("notes.txt"))
    .forEach(System.out::println);

Writing a File

Files.writeString(Path.of("output.txt"), "Hello file");
// append mode
Files.writeString(Path.of("log.txt"), "new line\n", StandardOpenOption.APPEND);

Exception Handling

Path path = Path.of("maybe-missing.txt");
try {
    String data = Files.readString(path);
    System.out.println(data);
} catch (IOException e) {
    System.out.println("Could not read file: " + e.getMessage());
}

File operations throw checked IOException, so you must handle or declare them.

Old-Style Streams (still used in APIs)

try (BufferedReader reader =
         new BufferedReader(new FileReader("notes.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
}

// Writing
try (BufferedWriter writer =
        new BufferedWriter(new FileWriter("out.txt"))) {
    writer.write("First line");
    writer.newLine();
    writer.write("Second line");
}

Checking Files

Path p = Path.of("data");
System.out.println(Files.exists(p));
System.out.println(Files.isDirectory(p));
System.out.println(Files.size(p));

Key Points

  • java.nio.file.Files makes text I/O short and safe.
  • Always handle IOException for file operations.
  • try-with-resources removes the need to close manually.
Share this post:

Comments (0)

Please login or register to comment.