Reading Files in Java (AP CSA 2025)
Reading files in Java is a new topic for the 2025-2026 exam. In this post, we'll review what we need to get started!
Reading one line from a file
To read one line, we import the necessary libraries from Java, add "throws IOException" to our main, create a File object, and create a Scanner object to read from that file. Then, we use the Scanner object to read one line from our main. At the end of our code, we close the Scanner.
import java.io.*;
import java.util.*;
public class Main {
public static void main(String [] args) throws IOException {
File myFile = new File("test.txt");
Scanner myScanner = new Scanner(myFile);
System.out.println(myScanner.nextLine();
myScanner.close();
}
}
Reading all lines from a file
Using a while loop and Scanner's hasNext method (which returns a boolean), we can read the entire contents of a file
import java.io.*;
import java.util.*;
public class Main {
public static void main(String [] args) throws IOException {
File myFile = new File("test.txt");
Scanner myScanner = new Scanner(myFile);
while(myScanner.hasNext()) {
String line = myScanner.nextLine();
System.out.println(line);
}
myScanner.close();
}
}
Splitting lines by spaces
Using the String split() method, we can split a line of text into an array of strings and use a loop to print all of them.
import java.io.*;
import java.util.*;
public class Main {
public static void main(String [] args) throws IOException {
File myFile = new File("test.txt");
Scanner myScanner = new Scanner(myFile);
while(myScanner.hasNext()) {
String line = myScanner.nextLine();
String[] words = line.split(" ");
for (String word : words) {
System.out.println("word: " + word);
}
System.out.println("---------");
}
myScanner.close();
}
}
Reading individual variables
The Scanner class also has methods for reading individual variables at a time. In the following example, we can read an int, double, boolean, and string from our test.txt file
import java.io.*;
import java.util.*;
public class Main {
public static void main(String [] args) throws IOException {
File myFile = new File("test.txt");
Scanner myScanner = new Scanner(myFile);
int myInt = myScanner.nextInt();
double myDouble = myScanner.nextDouble();
boolean myBoolean = myScanner.nextBoolean();
String myString = myScanner.next();
if(myBoolean == true) {
System.out.println(myString);
System.out.println(myDouble * myInt);
}
myScanner.close();
}
}
Review
In this post, we reviewed a few variations of reading files in Java. If you'd like to try out these code snippets, https://pickcode.io is a great online IDE for Java and AP CSA.