Skip to main content

Unit 4 · Topic 4.6

4.6 Using Text Files

New in the 2025 course. A text file stores data that's still there after your program stops. This topic covers opening a file with File and Scanner, the throws IOException rule, the Scanner methods for reading values, looping with hasNext, closing the file, and splitting a line with split.

Key terms

  • File
  • Scanner
  • throws IOException
  • hasNext
  • nextLine
  • split

Files and the classes you need

Variables disappear when a program ends. A file keeps its data even after a program stops running, so a program can read data that was saved earlier.

You connect a program to a file with two classes. A File object names the file: new File("laps.txt"). A Scanner built from it reads the contents: new Scanner(new File("laps.txt")). File and IOException are in the java.io package and Scanner is in java.util, so the program needs import statements for them.

Java requires you to say what happens if the file can't be opened. In this course you do that by writing throws IOException at the end of the header of any method that opens a file. Then, if no file has that name, the program stops with an error.

Reading values

These Scanner methods are on the Java Quick Reference. Values in a file are separated by spaces or line breaks.

MethodWhat it does
nextInt()reads the next value as an int; throws an InputMismatchException if it isn't one
nextDouble()reads the next value as a double; same exception if it can't
nextBoolean()reads the next value as a boolean; same exception if it can't
next()reads the next value as a String, stopping at a space or line break
nextLine()reads the rest of the current line as a String
hasNext()returns true if there's anything left to read
close()closes the scanner when you're finished with the file

Looping through a file

When you don't know how many values a file holds, loop with hasNext() as the condition, and call close() after the loop:

public static int sumFile(String fileName) throws IOException { Scanner input = new Scanner(new File(fileName)); int total = 0; while (input.hasNext()) { total += input.nextInt(); } input.close(); return total; }

If laps.txt holds 12 15 on one line, 9 on the next and 20 7 on the last, this returns 63. Line breaks don't matter to nextInt.

Splitting a line

Data files often put several fields on one line with a separator, like Leo,12. Read the whole line with nextLine(), then break it apart with the String method split, which returns a String array of the pieces between the separators. Convert number pieces with Integer.parseInt or Double.parseDouble (4.7).

import java.io.File; import java.io.IOException; import java.util.Scanner; public class RosterReader { public static void printNames(String fileName) throws IOException { Scanner input = new Scanner(new File(fileName)); while (input.hasNext()) { String line = input.nextLine(); String[] parts = line.split(","); String name = parts[0]; int grade = Integer.parseInt(parts[1]); if (grade >= 11) { System.out.println(name); } } input.close(); } }

Not on the exam

Reading from the keyboard isn't tested. Neither is code that mixes nextLine with the other reading methods on the same file, and you'll only split on simple separators like a comma or a space, not special pattern characters.

Worked examples

Try each one yourself first, then open the solution.

  1. Example 1

    Reading lines and splitting them

    The file roster.txt has four lines: Ava,10, Leo,12, Mia,11 and Sam,9. What does RosterReader.printNames("roster.txt") print?import java.io.File; import java.io.IOException; import java.util.Scanner; public class RosterReader { public static void printNames(String fileName) throws IOException { Scanner input = new Scanner(new File(fileName)); while (input.hasNext()) { String line = input.nextLine(); String[] parts = line.split(","); String name = parts[0]; int grade = Integer.parseInt(parts[1]); if (grade >= 11) { System.out.println(name); } } input.close(); } }

    Show the solution
    1. Step 1: The loop runs while the file has more to read. Each pass reads one whole line with nextLine().
    2. Step 2: split(",") breaks "Ava,10" into the array {"Ava", "10"}. parts[0] is the name and parts[1] is the grade as a String.
    3. Step 3: Integer.parseInt(parts[1]) turns "10" into the int 10, so it can be compared with 11.
    4. Step 4: Ava (10) and Sam (9) are skipped. Leo (12) and Mia (11) are printed, in file order.
    5. Step 5: After the loop, close() closes the file.

    Answer: Two lines: Leo, then Mia.

  2. Example 2

    split and parseDouble

    What does this code print?String line = "Lima,Peru,10.7"; String[] parts = line.split(","); System.out.println(parts.length + " " + parts[1]); double pop = Double.parseDouble(parts[2]); System.out.println(pop * 2);

    Show the solution
    1. Step 1: Splitting "Lima,Peru,10.7" on commas gives three pieces: "Lima", "Peru" and "10.7". So parts.length is 3 and parts[1] is "Peru".
    2. Step 2: Double.parseDouble("10.7") is the double 10.7, and doubling it gives 21.4.

    Answer: Two lines: 3 Peru, then 21.4.

Common mistakes

  • Forgetting throws IOException on the method that creates the Scanner from a File. The code won't compile without it.
  • Calling nextInt() when the next value is a word. That throws an InputMismatchException.
  • Doing math on a piece from split without converting it. "12" + 1 is "121"; use Integer.parseInt first.
  • Forgetting that split pieces start at index 0, so the second field is parts[1].

On the exam

  • This topic was added in the 2025 course update, along with File, Scanner, split, parseInt and parseDouble on the Java Quick Reference. Expect multiple-choice questions that show a file's contents and a reading loop and ask what's printed or stored.

Connected topics

Videos

Check yourself

4 questions on 4.6 Using Text Files. Pick an answer to see if you got it, and why.

Question 1 of 4

The text file scores.txt contains the following lines. Ana 88 Ben 92 Cal 75 Consider the following method.public static void report() throws IOException { Scanner input = new Scanner(new File("scores.txt")); int count = 0; int total = 0; while (input.hasNext()) { String name = input.next(); int score = input.nextInt(); count++; total += score; } input.close(); System.out.println(count + " " + total); }What is printed when report() is called?

Question 2 of 4

Consider the following method, which appears in a class that imports java.io.File, java.io.IOException and java.util.Scanner.public static int countWords() { Scanner input = new Scanner(new File("words.txt")); int count = 0; while (input.hasNext()) { input.next(); count++; } input.close(); return count; }The method does not compile. Which of the following changes fixes the problem?

Question 3 of 4

Consider the following code segment.String line = "red,green,,blue"; String[] parts = line.split(","); System.out.println(parts.length + " " + parts[2].length());What is printed as a result of executing the code segment?

Question 4 of 4

The text file sales.txt contains the following lines. 3,4 10,2 7,7 Each line holds a quantity and a price. Consider the following code segment, which appears in a method whose header includes throws IOException.Scanner input = new Scanner(new File("sales.txt")); int total = 0; while (input.hasNext()) { String line = input.nextLine(); String[] parts = line.split(","); total += Integer.parseInt(parts[0]) * Integer.parseInt(parts[1]); } input.close(); System.out.println(total);What is printed as a result of executing the code segment?

0 of 4 answered