4.6 - Using Text Files

superdancer16

Introduction

Welcome to the FiveHive website article for topic 4.6!

Today, our learning targets, according to AP® Computer Science A Course and Exam Description 2025, are as follows:

4.6.A Develop code to read data from a text file.

So far, we've worked with data created directly in our programs, particularly when values assigned to variables or stored in arrays using initializer lists. But real programs often need to work with external data stored in files. The question now becomes… how do we read the data in said files? Well in this article, you’ll find out!

A file is a kind of storage where the data stays even when a program is not running. Unlike variables that disappear when your program ends, data in files remains saved on disk. The data in a file can be retrieved during program execution, which makes it much easier to process large quantities of data.

We’re particularly going to cover the and classes for reading text files, handling potential errors with , and processing file contents using various  methods.

Anyway, let’s stop the spoilers! Sit back, grab a snack, and let’s get on with this lesson’s plan of attack! Get excited!

File and Scanner Classes

We use the  and classes to actually access the file in our programs! For the former, , you can use it to open files by creating an object of that class, using the name of the file as the argument of the constructor. Below is the syntax:

— creates a object where is the pathname for the file

Still not clear? Here’s an example:

File inputFile = new File("data.txt");

This creates a object representing the file in the same directory as your program. Once you have a object, create a to read from it:

— creates a that reads from the specified 

Here is an example:

File inputFile = new File("scores.txt");

Scanner fileScanner = new Scanner(inputFile);

Import Statements and IOException

Required Imports

The and classes are external classes that aren’t in the base Java program. Instead, they are a part of the package, which must be imported in order to be used. This can be done via the following:

Or import the entire package:

import java.io.*;

The class is in :

import java.util.Scanner;

Handling IOException

Sometimes when you use the  class… uh oh, a file cannot be opened! When that happens, your program has to have a mechanism to handle that case. One way to do this is to simply include a ““ to the header of the method that uses the file.

import java.io.*;
import java.util.Scanner;

public class FileReader {
    public static void readFile() throws IOException {
        File inputFile = new File("data.txt");
        Scanner scan = new Scanner(inputFile);
        // Read from file...
        scan.close();
    }
}

If the file name is invalid (file doesn't exist, wrong path, etc.), the program will crash with an error message.

Scanner Methods for Reading Files

The following methods work with files just like they work with other input sources:

Reading Primitive Types

: returns the next from the file. If the next value isn't a valid or doesn't exist, the program will throw an error.

: returns the next from the file. If the next value isn't a valid  or doesn't exist, the program will throw an error.

: returns the next from the file. If the next value isn't a valid or doesn't exist, the program will throw an .

Example file :

42
3.14
true

Reading code:

File f = new File("numbers.txt");
Scanner scan = new Scanner(f);

int num = scan.nextInt();           // → this variable will store 42
double decimal = scan.nextDouble(); // → this variable will store 3.14
boolean flag = scan.nextBoolean();  //→ this variable will store true

scan.close();

Reading Strings

: returns the next line of text as a . Can return an empty string if the line is blank.

: returns the next whitespace-delimited (reads until space, tab, or newline).

Example file :

Hello World
Java Programming

Reading with :

Scanner scan = new Scanner(new File("words.txt"));
String w1 = scan.next();     // → this variable will store "Hello"
String w2 = scan.next();     // → this variable will store "World"
String w3 = scan.next();     // → this variable will store "Java"
String w4 = scan.next();     // → this variable will store "Programming"
scan.close();

Reading with :

Scanner scan = new Scanner(new File("words.txt"));
String line1 = scan.nextLine();  // → this variable will store "Hello World"
String line2 = scan.nextLine();  // → this variable will store "Java Programming"
scan.close();

Checking for More Data

:  returns if there is a next item to read in the file; returns otherwise.

This is essential for processing files of unknown length.

Closing Files

: closes the scanner and releases file resources.

A file should be closed when the program is finished using it. Always call when done reading.

Reading Files with While Loops

A loop can be used to detect if the file still contains elements to read by using the method as the condition of the loop. For example:

File f = new File("data.txt");
Scanner scan = new Scanner(f);

while (scan.hasNext()) {
    String data = scan.next();
    System.out.println(data);
}

scan.close();

This pattern processes every item in the file without knowing the file size in advance.

Here’s a more substantial example:

File :

10
20
30
40
50

Code:

import java.io.*;
import java.util.Scanner;

public class FileSum {
    public static void main(String[] args) throws IOException {
        File f = new File("numbers.txt");
        Scanner scan = new Scanner(f);
        
        int sum = 0;
        while (scan.hasNext()) {
            int num = scan.nextInt();
            sum += num;
        }
        
        scan.close();
        System.out.println("Sum: " + sum);  // The while loop was used to add all the numbers in the file. Thus, this variable will be “150”.
    }
}

String split Method

The following additional method is useful for processing file data:

— returns a array where each element is a substring of this , which has been split around matches of the given delimiter .

Example with comma-separated values:

String line = "Alice,85,92,78";
String[] parts = line.split(",");
// parts[0] is "Alice"
// parts[1] is "85"
// parts[2] is "92"
// parts[3] is "78"

Alright, that’s all for content. Time for practice!