Dove's LibraryDove's Library

4.6 - Using Text Files

A file stores data that sticks around even after the program stops running. You can read that data back in later.
To connect a file to your program, you use the File and Scanner classes together.
import java.io.File; import java.io.IOException; import java.util.Scanner; public void readFile() throws IOException { File file = new File("data.txt"); // opens the file Scanner scanner = new Scanner(file); // ... read from it here scanner.close(); }
new File("data.txt") uses the File(String str) constructor. The String is the file’s name, or more exactly its pathname (where to find it). A plain name like "data.txt" means the file is in the same folder the program runs from.
You have to tell Java what to do if the file can’t be found, and the simplest way is adding throws IOException to your method header. If the file name turns out invalid, the program just terminates.
File and IOException both live in java.io, so you need to import them.
Scanner comes from a different package, java.util, which is why the example above has three import statements.

Scanner Methods for Reading Files

Scanner(File f) // constructor, wraps a File for reading int nextInt() // reads the next int (throws InputMismatchException if not an int) double nextDouble() // reads the next double boolean nextBoolean() // reads the next boolean String nextLine() // reads the next full line as a String String next() // reads the next single String (up to whitespace) boolean hasNext() // true if there's still something left to read void close() // closes the scanner
A few details about these methods:
  • next reads the next token, a chunk of text with no whitespace in it. Spaces, tabs, and line breaks all separate tokens, and next skips right over them.
  • nextInt, nextDouble, and nextBoolean also read one token, then convert it. If that token isn’t the right type (like the word cat when you call nextInt), or it’s a whole number too big to fit in an int, you get an InputMismatchException. nextDouble does accept a whole number like 5 and gives back 5.0.
  • nextLine reads everything left on the current line, spaces included, and returns it as a String. If it’s called right after another Scanner method, it can return an empty string (just the leftover end of the line the other method was reading).
  • hasNext doesn’t read anything. It only checks whether there’s another token left, which makes it the perfect loop condition.
  • close closes the scanner. Call it when you’re done reading the file.
Two things the AP exam leaves out: reading input from the keyboard, and code that mixes nextLine with the other reading methods (like nextInt) on the same file. Exam code reads a file either line by line with nextLine, or token by token with next, nextInt, nextDouble, and nextBoolean.
A common pattern: use a while loop with hasNext() as the condition to read through an entire file.
Scanner scanner = new Scanner(file); while (scanner.hasNext()) { String word = scanner.next(); System.out.println(word); } scanner.close(); // always close it when you're done
Here’s a full program. Say numbers.txt holds:
12 7 30 5 18
import java.io.File; import java.io.IOException; import java.util.Scanner; public class SumFile { public static void main(String[] args) throws IOException { File file = new File("numbers.txt"); Scanner input = new Scanner(file); int total = 0; while (input.hasNext()) { total += input.nextInt(); } input.close(); System.out.println(total); // 72 } }
The line break between 30 and 5 doesn’t matter, nextInt skips line breaks just like spaces. The loop stops once hasNext returns false, and then the file is closed.
There’s also a String method that’s handy for parsing file data:
String[] split(String del) // splits a string into an array around a delimiter
String line = "Alex,16,Junior"; String[] parts = line.split(","); // {"Alex", "16", "Junior"}
split is great for files where each line holds several values separated by commas. Read each line with nextLine, split it, then convert the number pieces with Integer.parseInt or Double.parseDouble (4.7). Say scores.txt holds:
Ana,88 Ben,72 Chloe,95
// inside a method whose header has throws IOException Scanner input = new Scanner(new File("scores.txt")); int total = 0; int count = 0; while (input.hasNext()) { String line = input.nextLine(); // "Ana,88" String[] parts = line.split(","); // {"Ana", "88"} int score = Integer.parseInt(parts[1]); // 88 System.out.println(parts[0] + " scored " + score); total += score; count++; } input.close(); System.out.println((double) total / count);
This prints Ana scored 88, Ben scored 72, and Chloe scored 95 on separate lines, then the average, 85.0.
The String you pass to split is technically a regular expression, a pattern format where some characters (like . and *) have special meanings. The exam stays away from those special characters and only splits on simple separators like a comma or a space.

AP® is a registered trademark of the College Board, which is not affiliated with Dove's Library and was not involved in the production of, and does not endorse, this website.

Providing free, high-quality AP notes to help students succeed, earn college credit, and reach their educational goals, ensuring everyone has access to the resources they need.

© 2026 Standard Learning Group, Inc., which operates Dove's Library. All rights reserved.