Skip to main content

Language Features

File Handling

Complete lesson for File Handling using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.

L1

Basics — File Handling

Section: Language Features. java.io and java.nio.file: Path, Files, readers/writers, and try-with-resources.

Two APIs: java.io.File and NIO.2

  • java.io.File is the older abstract pathname. Prefer java.nio.file.Path + Files (Java 7+) for new code.
  • Path is obtained from Path.of("notes.txt") (Java 11) or Paths.get(...).
  • Always specify a charset (UTF_8) when reading/writing text.
TaskModern APIClassic API
Read whole fileFiles.readString(path) (Java 11)FileReader + loop
Write whole fileFiles.writeString(path, text)FileWriter
Line by lineFiles.lines or BufferedReaderBufferedReader.readLine
Check existsFiles.exists(path)file.exists()
List directoryFiles.list / walkfile.listFiles()

try-with-resources

  • Any AutoCloseable (Reader, Writer, InputStream, Scanner on a file) should be opened in try ( ... ). close() runs even if you throw.
  • Do not swallow IOException. Declare throws IOException on main in small programs or catch and rethrow as unchecked.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class FileBasics {
    public static void main(String[] args) throws IOException {
        Path path = Path.of("hello.txt");
        Files.writeString(path, "Hello, file!\n", StandardCharsets.UTF_8);
        String text = Files.readString(path, StandardCharsets.UTF_8);
        System.out.print(text);
    }
}

Buffered line I/O

  • BufferedReader / BufferedWriter wrap character streams for efficient line reads and writes.
  • Files.newBufferedReader(path, UTF_8) is the NIO factory.
L2

Advanced — File Handling

Exceptions, atomic writes, and binary

  • File APIs throw **checked** IOException (and NoSuchFileException, AccessDeniedException). You must handle or declare them.
  • Files.readAllBytes / write for binary. Do not load multi-gigabyte files with readString.
  • For interviews, mention try-with-resources vs finally { if (br != null) br.close(); }.
  • Closing Scanner on System.in closes stdin — fine at the end of main, bad in libraries.
L3

Tricky Interview Points

Q1) File vs Path?

Answer File is the legacy pathname object. Path (NIO.2) plus Files is the modern API: better exceptions, symbolic links, and utilities.

Q2) What is try-with-resources?

Answer A try that declares AutoCloseable resources. Java calls close() automatically, including when an exception is thrown.

Q3) Why UTF-8 explicitly?

Answer Default charset used to be platform-dependent. Always pass StandardCharsets.UTF_8 so files are portable.

Q4) Is IOException checked?

Answer Yes. Callers must catch it or declare throws IOException.

Q5) How do you read a file line by line without loading it all?

Answer BufferedReader.readLine in a loop, or Files.lines (close the Stream).

Q6) What does Files.writeString do if the file exists?

Answer By default it truncates and overwrites. You can pass StandardOpenOption.APPEND to add to the end.

L4

Simple Programs

Write, read, and count lines

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 LineCount {
    public static void main(String[] args) throws IOException {
        Path path = Path.of("sample.txt");
        Files.writeString(path, "alpha\nbeta\ngamma\n", StandardCharsets.UTF_8);
        int lines = 0;
        try (BufferedReader br = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
            while (br.readLine() != null) {
                lines++;
            }
        }
        System.out.println("lines = " + lines);
    }
}
L5

Problem Solving Tricks

  • Use Path.of and Files for new code; keep File when an old API demands it (File ↔ path.toFile()).
  • try-with-resources can declare several resources, separated by ;.
  • Never ignore IOException with an empty catch.
  • Build paths with Path.of("dir", "file.txt") instead of string concatenation and \\.
L6

Practice Programs List

  1. Write three lines to a file and read them back with Files.readAllLines.
  2. Copy a text file using BufferedReader and BufferedWriter.
  3. Append a timestamp line with StandardOpenOption.APPEND (create the file if missing).
  4. List all .java files in a folder with Files.list and an endsWith filter.
  5. Handle a missing file and print a friendly message instead of a stack trace.