Overview
One learning objective, 4.6.A: develop code to read data from a text file. Day 1 is about getting a file open: why programs keep data in files (4.6.A.1), new Scanner(new File(name)) (4.6.A.2, 4.6.A.3), the imports from java.io (4.6.A.5), and throws IOException, which Java requires even before anything has gone wrong (4.6.A.4). Day 2 is the token readers from the Java Quick Reference (next, nextInt, nextDouble, nextBoolean; 4.6.A.6), a while (input.hasNext()) loop that reads a file of any length (4.6.A.9), and close (4.6.A.10). Day 3 puts the data in an array, contrasts next with nextLine (4.6.A.6, 4.6.A.7), and cuts each line into pieces with split (4.6.A.8).
Keep one routine running through all three days: open, read, close. Every program students see opens the file once, reads it in file order, and closes it after the last read.
Students know Scanner on a String (Topic 1.14), imports (Topic 1.7), String methods (Topic 1.15), while and for loops (Topics 2.7 and 2.8), and arrays with their standard algorithms (Topics 4.3 to 4.5). Stay inside the boundary and the exclusions:
- No keyboard input. Reading from the keyboard is outside the AP course (4.6.A.6 exclusion). Every program here reads a file.
- One style per file. Code that mixes
nextLinewith the otherScannermethods on the same file is excluded from the exam (4.6.A.7). Mention the empty-string problem so students know why the rule exists; do not teach code that adjusts for it. - Plain delimiters only.
split’s parameter is a regular expression, and special characters such as.and*are excluded (4.6.A.8). Use commas, colons, spaces, and hyphens. - Not yet:
Integer.parseIntand wrapper classes (Topic 4.7),ArrayList(Topic 4.8),try/catch(not in the course), and writing files (not in the course).
Teacher note
The slides are the Pond Log Files deck (21 slides, with speaker notes); slide numbers below refer to it. Day 1 uses slides 1–7, Day 2 uses slides 8–14, and Day 3 uses slides 15–21. The Pond Log Files puzzle worksheet (10 questions, about 30 minutes) is split across the days: question 3 rows 1–4 in class on Day 1; questions 1, 2, and 4 in class on Day 2, with 7 and 8 as Day 2 homework; question 5 and question 3 row 5 in class on Day 3, with 6, 9, and 10 as Day 3 homework.
All demonstration files are in the topic’s examples/ folder. Before Day 1, put the data files (temps.txt, player.txt, answer.txt, roster.txt, books.txt, grades.txt) in the folder the IDE runs programs from. A file in the wrong folder causes a FileNotFoundException that looks like a code bug; test one program on the projector machine first. If students’ IDE does not support data files, run the Day 1 guided practice as a whole-class demo.
- Day 1 demonstrations:
FirstFileRead,OneLineOpen,MissingFileImport,NoThrows,MissingFile,ScannerOnName,HelperReadandHelperMainNoThrows(optional). - Day 2 demonstrations:
ReadPlayer,ReadPlayerSpread,WrongOrder,BooleanYes,SumTemps,FixedCountLoop,ReadAfterClose. - Day 3 demonstrations:
GradeReport,ReadRoster,ReadRosterNext,BookList,SplitVariations,SplitSpaceAfterComma,ChessSignups. Files ending in.snippet.javahold only the statements insidemain; paste them into a scratch class to run them. - Printed only (exit ticket):
ExitWalks(withwalks.txt) andExitPlaylist(withplaylist.txt).
The slides read weather.txt (72 68 75 71); the study guide and the demo files read temps.txt (72 68 75 and 80 77 on two lines). Point out the difference once so students do not expect the slide’s output from the demo.
Day 1 · Warm-up: Where did the high score go?
Show slide 2. Partners answer the three questions; ask each student to write an answer to question 3 before they talk. Take answers: a variable lives in memory only while the program runs (1); when the program ends it is gone, and the next run starts fresh from the code (2); to survive, the 900 has to be stored outside the program, in a file (3). Write persists on the board: a file persists when no program is running (4.6.A.1).
Misconception: A variable remembers its value from the last run
Students expect highScore to start at 900 next time because that is what the game showed. Each run starts from the code, so it starts from whatever the code says. Ask, “Where in the code would 900 come from?” If nothing in the code or a file holds it, it is gone. The worksheet’s Watch Out after question 7 says the same thing, so point back to it there.
Day 1 goals and why files exist
Read the five goals on slide 3 aloud; goals 1 and 2 are today’s. Slide 4 opens Part 1. Give the recipe-and-pantry picture from the study guide: the program is the recipe, the file is the pantry. The weather club can add tomorrow’s temperature to the file without touching the program, and the same program reads whatever the file holds that day.
Day 1 · Direct instruction: File, Scanner, imports, throws IOException
- Your first file program (4.6.A.2, 4.6.A.3, slide 5). Walk through it line by line:
new File("weather.txt")names the file, andnew Scanner(...)connects to it and opens it. After that,nextIntworks exactly as it did on a string in Topic 1.14. Then switch to the IDE and runFirstFileRead(printsMonday: 72andTuesday: 68). ShowOneLineOpenas the same idea with theFileobject created inside theScannercall; the rest of the topic uses that form. - Three things Java insists on (4.6.A.4, 4.6.A.5, slide 6). Read the table row by row and ask for each, “Compile time or run time?” before revealing the last column.
- Missing
import java.io.File;: runMissingFileImport.cannot find symbol … class File.FileandIOExceptionare injava.io,Scannerinjava.util; onlyjava.langis automatic. - Missing
throws IOException: runNoThrows. Decode the message:FileNotFoundExceptionis the specific kind ofIOExceptiontheScannerconstructor can throw, and “declared to be thrown” is exactly whatthrows IOExceptiondoes. (“Caught” meanstry/catch, which is not in this course.) - No file with that name: covered next.
- Missing
- Why Java insists. A missing file is not a bug in the code; it depends on what is on the disk when the program runs. Java makes the method header admit that risk. If the file cannot be opened, the program terminates.
- One letter off (slide 7). Ask, “Does this compile?” before revealing the output. Run
MissingFile: it compiles, printsOpening the file..., then stops with aFileNotFoundExceptionat theScannerline. Creating aFileobject only records a name; the crash comes when theScannertries to open it. - Helper methods (optional, if time allows). Show
HelperRead, thenHelperMainNoThrows: a method that calls a method declaringthrows IOExceptionneeds the clause too. The slide 6 rule says “and every method that calls one”.
Misconception: The compiler will notice the file is missing
Students put “missing file” in the compile-error column. The compiler checks code, never the disk. Ask two questions of every file mistake: “Is the code itself wrong?” (compile error) and “Is the code fine but the disk is not?” (run-time error). Slide 6 and worksheet question 3 both turn on this difference.
Misconception: new Scanner("temps.txt") reads the file
It compiles, because Scanner has a constructor that takes a String, but it scans the nine characters of the name. Run ScannerOnName: the only token is temps.txt. A nextInt call there would throw an InputMismatchException. The fix is new Scanner(new File("temps.txt")). Worksheet question 3 row 4 and the question 4 decoy test this exact mistake.
Day 1 · Guided practice: Open a file, then break it three ways
Students create FirstFileRead in the IDE (or type it from the slide 5 frame) and run it on temps.txt. Then, one change at a time, they predict, run, record, and undo:
- Delete
import java.io.File;. - Delete
throws IOExceptionfrommain. - Change
"temps.txt"to"temp.txt". - Add another number to the end of
temps.txtand run the unchanged program.
For each, students record: did it compile, what printed, and what Java reported. Debrief: changes 1 and 2 are compile errors (nothing runs); change 3 compiles and terminates with a FileNotFoundException; change 4 changes nothing in the output, because this program reads only two values. Use change 4 to set up Day 2: “How would we read every value, however many there are?”
Teacher note
Have students change the file back after step 4, because Day 2’s demos assume the original five values. If the IDE runs programs from a different folder than the one that holds the data file, change 3’s error will appear for the unchanged program too; fix the folder before going on.
Day 1 · Independent practice: Independent practice
Students do worksheet question 3 (you’re the compiler), rows 1–4, alone. Row 1 is the missing throws, row 2 the missing File import, row 3 the missing file (compiles, then FileNotFoundException), and row 4 the String constructor (prints notes.txt). Row 5 uses split; it waits until Day 3.
Day 1 · Closure: Closure
Ask students to sort three mistakes on a mini whiteboard into “compiler finds it” and “crashes when it runs”: no import java.io.File;, a misspelled file name, no throws IOException. Answer: the first and third are compile errors; the misspelled name is a run-time FileNotFoundException.
Day 2 · Warm-up: Count the lines and the tokens
Write the study guide’s two-line file on the board, 72 68 75 and 80 77, and beside it the same tokens spread over four lines with an empty line and extra spaces. Students write the number of lines and tokens in each. Both have five tokens; one has two lines and the other four. Remind them of Topic 1.14: a Scanner splits text into tokens at whitespace, and spaces, tabs, and line breaks all count, however many in a row.
Day 2 · Direct instruction: The token readers
- The Scanner reading methods (4.6.A.6, slides 8–9). Slide 8 opens Part 2. On slide 9, cover the bottom three rows for now. Each token reader skips whitespace, reads one token, and moves past it.
nextBooleanis the new one: it turnstrueinto thebooleanvaluetrue. Each throws anInputMismatchExceptionwhen the next token is the wrong type;nextnever does, because any token is valid text. - Reading a record (slide 10). Trace the four calls on the slide before revealing the output.
truesits on the next line, andnextBooleanreads it anyway.speed * 2is7.0, adouble. RunReadPlayer, thenReadPlayerSpread: same tokens, scattered over four lines, same output. For token readers only the order of the tokens matters. - Mismatches. Run
WrongOrder:nextIntmeetsMayafirst and throws anInputMismatchException, and nothing prints. Then runBooleanYes(answer.txtholdsyes): onlytrueandfalsecount. Mention the other two mismatch cases without running them:nextIntrejects88.5, and it rejects3000000000because that is too big for anint(4.6.A.6: “out of range”).nextDoubledoes accept a whole number such as72, returning72.0.
Misconception: nextInt finds the next number
Students read nextInt as “search ahead for a number”. It only ever looks at the next token. Have students write the file’s tokens in a row and cross one off for every call; the type of each call must match the token it crosses off. The slide 11 bonus question and worksheet question 7 both depend on this.
Day 2 · Guided practice: Read in order
Slide 11. Students write the output alone, then compare with a partner. Answer: BenAna, then 10. The reads go Ana, 3, Ben, 7; b + a joins two Strings, and x + y adds two ints. Bonus: if the first call were nextInt(), the first token is Ana, so the program throws an InputMismatchException before printing anything.
Day 2 · Direct instruction: HasNext loops and close
- Keep reading while hasNext() (4.6.A.9, slides 12–13). Uncover the
hasNextrow of slide 9: it returnstruewhen another token is waiting, and it only looks; it never moves the scanner. Trace slide 13: four passes, sum 286, average 71.5. Then runSumTempsontemps.txt(five values:Readings: 5,Total: 372,Average: 74.4). Add three numbers to the file and run it again with no code change. - Reading a fixed number of times (slide 14). Ask what the
forloop prints before revealing it: four values, then aNoSuchElementExceptionon the fifth read. RunFixedCountLoop(six reads of five values) to see it live.NoSuchElementExceptionmeans there is nothing left to read;InputMismatchExceptionmeans there is a token but it is the wrong type. - Every pass must read. Write the word-counting loop from the study guide on the board (
while (input.hasNext())with onlywords++;in the body) and ask what happens. It never ends: nothing moves the scanner, sohasNext()staystrue. - Close after the last read (4.6.A.10). Uncover the
closerow of slide 9.close()gives the file back; after it, the scanner cannot be used. RunReadAfterClose: it printsFirst: 72, then throws anIllegalStateException: Scanner closed. In ahasNextloop,close()goes right after the loop.
Misconception: hasNext() reads the token
Students think checking hasNext() uses up a value, or that it guarantees as many reads as they like. It only looks, and one true guarantees one more token. A body that calls nextInt() twice (once in an if condition and once to print) skips values and can crash on the last pass. Teach “read once into a variable, then use the variable”; worksheet question 8 uses that shape.
Misconception: Read exactly as many times as I counted
Students look at the file, count five values, and write a for loop for five. The file changes and the program breaks: too few reads miss data, too many throw a NoSuchElementException. Unless the file itself states the count (Day 3’s grades.txt), let hasNext() decide.
Misconception: close() goes inside the loop, or not at all
A short program without close() usually works, so students skip it; others put it at the end of the loop body “so the file is closed”. Inside the loop, the first pass closes the scanner and the next hasNext() throws an IllegalStateException. Treat opening and closing as a pair: one close() after the last read. Worksheet question 8, claim 3, is this mistake.
Day 2 · Independent practice: Independent practice
Students work worksheet questions 1 (pencil check), 2 (you’re the JVM), and 4 (code tiles) in class. Check question 1 rows 4 and 8 as you circulate: hasNext() is true in row 4 and false in row 8. In question 4, the two decoys are the for loop (a fifth read that is not there) and new Scanner("laps.txt"). Questions 7 (one-token fix: nextInt to nextDouble) and 8 (two truths and a lie) are homework.
Day 2 · Closure: Closure
Each student writes one sentence: “Every pass of a hasNext() loop must …” Look for “read something”, so the scanner moves toward the end of the file.
Day 3 · Warm-up: How many times does the loop run?
Write roster.txt on the board (Ada Lovelace, Grace Hopper, Alan Turing) and a hasNext() loop that prints input.next() each pass. Ask how many passes and what prints. Six passes: Ada, Lovelace, Grace, and so on. Ask, “What if we wanted each full name on one line?” That is today’s question.
Day 3 · Direct instruction: From a file into an array
Slide 15. A common file layout stores the count first. Read it, use it as the array length, and fill the array with an indexed for loop; a for loop is fine here because the file says how many values follow. Once the data is in the array, every algorithm from Topic 4.5 works on it. Run GradeReport (Grades read: 5, Average: 87.2, Highest: 100) and point out that it closes the file as soon as the array is full, before the analysis loop.
Day 3 · Direct instruction: Tokens or whole lines
- Tokens or whole lines? (4.6.A.6, slides 16–17). Slide 16 opens Part 4. On slide 17, students predict both outputs before you reveal them.
nextstops at every space, so each name comes out in two pieces;nextLinereturns the rest of the line, spaces included, without the line break. RunReadRoster, thenReadRosterNext. - One style per file (4.6.A.7). A token reader stops right after its token and leaves the line break behind, so a
nextLinecall right afternextIntcan return an empty string. Code that adjusts for that is not on the exam. The rule for this course: read a file withnextLineor with the token readers, not both. Worksheet question 9 (the face-off) is built on this.
Misconception: next() and nextLine() do the same thing
Students use next() for a full name and lose half of it. Make the choice a question about the file: “Does one piece of data have a space inside it?” If yes, read lines. Slide 17 shows the two outputs side by side.
Day 3 · Direct instruction: Split
- split cuts a line at a delimiter (4.6.A.8, slide 18).
splitreturns aStringarray of the pieces between the delimiters, in order, with the delimiters removed. Fill the index table on the slide with the class:parts.lengthis 3,parts[1]keeps its space, andparts[2]is theString"1965", not a number. RunBookList. - Change only the delimiter. Run
SplitVariations: splitting on" "gives two pieces with the commas still inside; splitting on";", which never appears, gives one piece, the whole string.splitalways returns at least one element. - Matched exactly. Run
SplitSpaceAfterComma:","leaves a leading space on" 92", and", "removes it. Then put"red,,blue,green"on the board: two commas in a row make an empty piece. - Plain delimiters only. Characters such as
.,*, and|have special meanings tosplit, and that pattern language is not part of the course. Stick to commas, colons, semicolons, spaces, and hyphens. - Putting it together (if time allows).
ChessSignupsreads lines, splits each one, and counts the chess signups withequals.
Misconception: split gives back numbers
"1965" from split is text, so parts[2] + 1 is "19651", not 1966. Students meet this in slide 19’s last line and in the worksheet’s Fair Question after question 5. Tell them Topic 4.7 shows how to turn text into a number; until then, numbers needed for arithmetic come from files read with nextInt or nextDouble.
Misconception: The delimiter is always a space
Token readers split at spaces, so students expect split to as well, or they pick ", " when the file has no spaces after its commas. The delimiter is whatever is passed, matched character for character. Have students point to the exact characters between two fields in the file before choosing it.
Day 3 · Guided practice: Predict the pieces
Slide 19. Students write all four lines alone. Answer: 3, 30, 1, and 451. "a-b-c" has no spaces, so the whole string is the only piece; t[2] is the String "45", so + 1 joins text.
Day 3 · Independent practice: Independent practice
Students do worksheet question 5 (snippet pool: nextLine(), ",", 0) and return to question 3 row 5 (int n = p[0]; does not compile, because p[0] is a String). Questions 6 (match-up), 9 (face-off), and 10 (wrap-up) are homework. In question 6, watch for students who count only two pieces in "red, green,,blue": three commas make four pieces, and the piece at index 2 is empty.
Day 3 · Closure: Closure
Slide 20 is the vocabulary; point to a card and ask for the line of code it goes with. Then slide 21: partners explain, with the sentence starter, how a program reads every number in a file it has never seen. Cold-call two pairs. Listen for new Scanner(new File(name)) with the imports and throws IOException, a while (input.hasNext()) loop with one read per pass, and close() after the loop.
Day 3 · Exit ticket: Exit ticket
Give the exit ticket for the last 5 minutes. Question 1 checks the token readers and the hasNext loop (4.6.A.6, 4.6.A.9), question 2 the compile-time rules for opening a file (4.6.A.4, 4.6.A.5), and question 3 choosing a correct nextLine and split loop with close (4.6.A.8, 4.6.A.10). Re-teach the weakest one before Topic 4.7, which builds on split returning text.