Scanner reads and parses data, BufferedReader efficiently reads character data, and FileWriter writes character data to a file. In IB Computer Science topic B2.5 File processing, you should distinguish their direction of data flow and how each class handles data.
| Java class | Main purpose | Important methods or behaviour |
|---|---|---|
Scanner | Reads input and converts tokens into values such as integers, doubles, or strings | nextInt(), nextDouble(), next(), nextLine(), and hasNext() |
BufferedReader | Reads character data efficiently by storing input temporarily in a buffer | read(), readLine(); readLine() returns null at the end of the file |
FileWriter | Writes characters or strings to a text file | write(), append(), and close() |
A Scanner can be connected to a File. It separates input into tokens and parses those tokens into specified data types. This makes it convenient when a file contains structured values, such as names followed by test scores.
A BufferedReader is commonly connected to a FileReader. It reads blocks of characters into memory, reducing the number of direct file-access operations. It is therefore suitable for reading text line by line, although values must be converted manually, for example with Integer.parseInt().
A FileWriter transfers character data from the program to a text file. By default, opening an existing file with new FileWriter("results.txt") overwrites its contents. Using new FileWriter("results.txt", true) enables append mode, adding data to the end instead.
These classes should be closed after use so that system resources are released and buffered output is completed. A try-with-resources statement closes them automatically, including when an exception occurs.
A common misconception is that FileWriter can read files because it accesses a file. It cannot: it only writes character data.
For an IB exam response, state each class's purpose, identify whether it performs input or output, and explain buffering or parsing where relevant. In code-tracing questions, watch for end-of-file checks, append mode, type conversion, and proper resource closure.