AP® Computer Science A · Unit 4 · Topic 4.6
Opening a File with File and Scanner
A File object names a path on disk, and a Scanner wraps that File to actually read its contents, while throws IOException tells Java the method hands off responsibility if the file can't be found.
Data in a file outlives the program because it lives on disk, not in memory. Variables and objects vanish the instant a program ends, but a file sits there on storage until something deletes it or writes over it. That's the whole point of files: they let one run of a program save something a later run, or a different program, or a human with a text editor, can pick back up.
To read that surviving data, Java needs two pieces working together. A File object is just an address — it holds a path like scores.txt and knows nothing about what's inside. It opens nothing and reads nothing by itself. A Scanner is the thing that actually does the reading: when you build a Scanner around a File, it opens a stream of bytes from disk and lets you pull out ints, doubles, and lines with the same methods you already use for System.in. The File names the destination; the Scanner builds the pipe and walks it.
Opening a file can fail — the path might be wrong, the file might not exist, a disk might be unreadable. Java forces you to acknowledge that risk through IOException, a checked exception. A method that opens a file and declares throws IOException isn't fixing the problem; it's telling the compiler and any caller that this failure is possible and that responsibility for handling it is being passed up the call chain. This sets up try-catch, covered next, as the other way to deal with that same risk.
Key terms
- File
- An object representing a path to a location on disk, without opening or reading its contents.
- Scanner
- A class that can wrap a File to open a stream and read its contents piece by piece.
- IOException
- A checked exception signaling that an input or output operation, like opening a file, may fail.
- throws clause
- A method header declaration that passes responsibility for handling a checked exception to the caller.
- checked exception
- An exception the compiler forces you to handle or declare with throws before the code will compile.
Watch it explained
- How it worksHow does a File object plus a Scanner build a pipe from the disk into your program?
- Worked exampleWalk me through the lines that open scores.txt and get a Scanner reading from it.
- How it worksHow does throws IOException tell Java what to do when the file is not there?
- Common mistakeWhy isn't creating a File object the same as opening or reading the file?
Check yourself
End of topic.