Codectionary / Developer documentation / Java

Java File Handling

Use Path to identify a file and Files to read or write it. These examples require Java 11 or later. Save each as Main.java, then run javac Main.java and java Main. I/O operations can throw IOException.

Syntax

Path path = Path.of("notes.txt");
String text = Files.readString(path, StandardCharsets.UTF_8);
Files.writeString(path, "Updated notes", StandardCharsets.UTF_8);

Examples

Write, append and read text

Prints HTML and CSS on separate lines. Uses a temporary file and deletes it afterward.

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class Main {
  public static void main(String[] args) throws IOException {
    Path file = Files.createTempFile("codectionary-", ".txt");
    try {
      Files.writeString(file, "HTML\n", StandardCharsets.UTF_8);
      Files.writeString(file, "CSS\n", StandardCharsets.UTF_8, StandardOpenOption.APPEND);
      System.out.print(Files.readString(file, StandardCharsets.UTF_8));
    } finally {
      Files.deleteIfExists(file);
    }
  }
}

Read one line at a time

The reader closes before cleanup, including when reading fails.

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
  public static void main(String[] args) throws IOException {
    Path file = Files.createTempFile("topics-", ".txt");
    try {
      Files.writeString(file, "Arrays\nMethods\n", StandardCharsets.UTF_8);
      try (BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
        String line;
        while ((line = reader.readLine()) != null) {
          System.out.println(line);
        }
      }
    } finally {
      Files.deleteIfExists(file);
    }
  }
}

Best practices

  • Use UTF-8 explicitly for text. Binary files require byte-oriented methods.
  • writeString replaces existing contents by default. Use APPEND when you intend to add text.
  • Use buffered reading for large files and try-with-resources to close readers. Path itself does not need closing.
  • These examples declare throws IOException to keep failures visible. Handle failures where an application can recover or explain the problem.
  • Relative paths use the current working directory. Temporary practice files are not persistent storage.

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading