Using Text Files
| English | Chinese | Pinyin |
|---|---|---|
| text file | 文本文件 | wén běn wén jiàn |
Reading a file
- A text file 文本文件 stores data as lines of characters on disk.
- Java reads one with a
Scannerattached to aFile, not toSystem.in. Scanner in = new Scanner(new File("data.txt"));- The same
Scannermethods you know (nextInt,nextLine, …) then read the file.
Line by line
in.hasNextLine()istruewhile there are more lines to read.- Loop:
while (in.hasNextLine()) { String line = in.nextLine(); ... } - Each pass reads one line; the loop ends when the file runs out.
- This "while there's more" pattern processes a file of unknown length.
Reading tokens
in.hasNext()/in.next()read one token (word) at a time.in.hasNextInt()/in.nextInt()read numbers.- Choose line-based or token-based reading to match the file's format.
- Store what you read into variables, arrays, or an ArrayList.
Closing the file
- When done, close the Scanner:
in.close();to release the file. - Reading a file can fail (missing file) — the AP handles this with a
throwsclause onmain. - Don't read past the end — the
hasNext…check guards against it. - The file's data now lives in your program's variables to process.
Reading a text file
Follow the steps a program takes to read a file line by line.
Guard file reads with hasNextLine() / hasNext() before each read. Calling nextLine() when the file is exhausted throws an exception. The pattern is always check, then read: while (in.hasNextLine()) { ... in.nextLine() ... }. A file Scanner reads from a File object, unlike the System.in Scanner for keyboard input.
Reading every line of a file:
Scanner in = new Scanner(new File("scores.txt"));while (in.hasNextLine()) { String line = in.nextLine(); process(line); }in.close();
Read a text file with a Scanner attached to a File. Loop while hasNextLine() (or hasNext() for tokens) and read with nextLine()/next()/nextInt() — always check before reading to avoid running past the end. Close the Scanner when done.
To read a text file, you attach a Scanner to a...
new Scanner(new File("...")) reads a file.
Which method checks whether there is another line to read?
hasNextLine() guards a nextLine() read.
You should check hasNextLine() before each call to nextLine().
Reading past the end throws an exception.
When you finish reading a file, you should...
in.close() releases the file.
The same Scanner methods (nextInt, nextLine) work for both keyboard and file input.
Only the source (System.in vs File) differs.