Skip to content

Chapter 21 of 37

File I/O

Read and write bytes, characters, buffered streams, Paths, and Files safely.

42 minutes 10 quick checksBy Subha Prasad
Lesson 21 of 37Course navigation

Lesson content

Read, practise, then check your understanding

Byte streams use InputStream/OutputStream; character I/O uses Reader/Writer with a charset. NIO Path and Files provide concise filesystem operations.

Explicit encoding and cleanup

Path path = Path.of("notes.txt");
try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
    writer.write("Java\n");
}

try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
    lines.forEach(System.out::println);
}

Buffer repeated small operations, check size before loading untrusted files, normalize and constrain user-controlled paths, and handle partial failure. Files.move can support temporary-file replacement. Never rely on the platform default charset for durable interchange. Streams from Files.lines hold resources and must be closed.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes InputStream?
Which Java term matches this description: The base abstraction for reading bytes.
Which statement best describes Reader?
Which Java term matches this description: The base abstraction for reading characters.
Which statement best describes Writer?
Which Java term matches this description: The base abstraction for writing characters.
Which statement best describes Path?
Which Java term matches this description: An NIO representation of a filesystem path.
Which statement best describes try-with-resources?
Which Java term matches this description: A statement that closes declared resources in reverse order.

0 of 10 checks passed

Your progress is saved on this device.

File I/O | Java Lesson | Subha Prasad