File Handling in Java

Lesson 20 of 20

Read and write real files — open streams, loop line by line with BufferedReader and always close what you open.

The big picture

Streams to disk and back

Java treats files as streams of characters. FileWriter pushes text out; BufferedReader pulls it back in, one comfortable line at a time.

FileWriter writes

new FileWriter("note.txt") opens (or creates) a file and hands you a stream to write into.

BufferedReader reads

readLine() returns the next line, or null at end of file — the natural loop condition.

Checked exceptions

File operations can fail, so the compiler demands a catch or a throws on the method.

close() is mandatory

Closing flushes buffers and releases the file handle — always close, even after a crash.