AP® Computer Science A · Unit 4 · Topic 4.6
Reading a File Line by Line into a Collection
Reading a file means stepping through it from the top using a loop that checks hasNext before each read, storing each line's value into a collection until no input remains.
A file is stored as a stream of characters, not a labeled array of lines you can jump into. A Scanner reads that stream from the start, one token or line at a time, and has no way to skip to line 7 without passing through lines 1 through 6 first. That is why file reading is sequential: you process what comes next, then advance.
The loop condition does the real work. A while loop built on hasNext() (or hasNextLine(), hasNextInt()) asks the Scanner 'is there more input of this kind waiting?' before every pass. As long as the answer is true, the loop body reads one item with next() or nextInt() and adds it to an ArrayList, say. When the Scanner reaches the end of the file, hasNext() returns false, the loop stops, and the collection holds exactly one element per item read — a four-line file of numbers produces a list of size 4.
Mixing nextInt() and nextLine() trips people up because nextInt() only grabs the numeric token and leaves the rest of that line, including the leftover newline, sitting unread; a following nextLine() then grabs that leftover scrap instead of the next real line. This topic sits right before searching and sorting those loaded collections — you cannot binary search or sort an ArrayList you never finished reading, so getting the read loop exactly right matters for everything that follows.
Key terms
- Scanner
- The class used to read tokens or lines of text from a file or input source in order.
- hasNext()
- A method that returns true if another token remains to be read, acting as the loop's stopping test.
- nextInt()
- Reads and consumes the next token as an int, leaving any remaining text on that line unread.
- nextLine()
- Reads and consumes the rest of the current line, including leftover text after a prior nextInt() call.
- token
- A single unit of input, such as a word or number, separated from others by whitespace.
Watch it explained
- How it worksHow does hasNext act as the loop condition that stops at the end of a file?
- Worked exampleTrace reading a four-line file of numbers into an ArrayList and find its size after.
- Worked exampleFind what nextInt and nextLine each consume when a line holds 12 followed by a name.
- Common mistakeWhy doesn't hasNextInt returning false always mean the file has been finished?
Check yourself
End of topic.