← Chapter 9 — Files & Regular Expressions

32. File Handling

mixed

Description

Java can read and write files using the java.nio.file package. Path represents a file location and Files provides concise operations for common tasks.

File operations can fail because a file is missing, unavailable, or unreadable. Use try-with-resources for streams and handle IOException appropriately.

Subtopics

Paths

Description

Path describes a location in the file system.

Explanation

Paths.get creates a Path from readable path segments.

Example

java.nio.file.Path path = java.nio.file.Paths.get("scores.txt");

Reading and writing

Description

Files has convenient static methods for text.

Explanation

writeString and readString suit small text files.

Example

java.nio.file.Files.writeString(path, "Aditi: 92");

Explanation

Use relative paths carefully: they are resolved from the program's working directory. Print path.toAbsolutePath while debugging if a file seems to be in the wrong place.

Example

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class FileDemo {
    public static void main(String[] args) throws IOException {
        Path path = Path.of("student.txt");
        Files.writeString(path, "Rohan: 88");
        System.out.println(Files.readString(path));
    }
}

Key points

  • Path represents a file location.
  • Files reads and writes common formats.
  • File operations can throw IOException.

Open reference