01 / 20

Using Text Files
in Java

Master reading from and writing to text files using Java's I/O classes: from basic Scanner input to robust exception handling.

AP Computer Science A

What Are Text Files?

A text file stores data as a sequence of human-readable characters, organized line by line. Unlike binary files, you can open a text file in any editor and read its contents directly.

.txt
Plain text with no formatting: the simplest file type
.csv
Comma-separated values: tabular data in text form
.dat
Generic data files often read line by line in programs

Why Use Text Files?

1
Data persistence: Save results so they survive after the program ends.
2
Large input: Process hundreds of values without typing them every time.
3
Interoperability: Share data between programs, languages, and platforms.
4
Testing and debugging: Feed consistent test data from files instead of manual input.

The Java I/O Pipeline

Text File data.txt Scanner / BufferedReader reads line by line Your Program processes data PrintWriter READ PARSE WRITE

Reading with Scanner

import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ReadDemo { public static void main(String[] args) { try { Scanner sc = new Scanner(new File("data.txt")); while (sc.hasNextLine()) { String line = sc.nextLine(); System.out.println(line); } sc.close(); } catch (FileNotFoundException e) { System.out.println("File not found!"); } } }

Writing with PrintWriter

import java.io.PrintWriter; import java.io.FileNotFoundException; public class WriteDemo { public static void main(String[] args) { try { PrintWriter out = new PrintWriter("output.txt"); out.println("Hello, file!"); out.println("Score: " + 95); out.close(); // MUST close to flush data } catch (FileNotFoundException e) { System.out.println("Cannot create file!"); } } }

Scanner vs BufferedReader

Scanner BufferedReader
Package java.util java.io
Parses tokens? Yes: nextInt(), nextDouble() No: returns Strings only
Speed Slower (regex parsing) Faster (buffered reads)
Exception FileNotFoundException IOException
AP CSA Focus ★ Primary Good to know

Handling Exceptions

try { ... } Risky code goes here new Scanner(new File(...)) new PrintWriter(...) sc.nextLine() ✓ Success continues normally ✕ Exception jumps to catch catch { ... } Handle the error Print message, log, etc. finally { ... } Always runs Close resources here no error error!

Step-by-Step: Reading a File

1
Import java.io.File, java.util.Scanner, and java.io.FileNotFoundException.
2
Create a File object with the path: new File("data.txt")
3
Wrap it in a Scanner inside a try-catch block.
4
Loop with hasNextLine() or hasNext() to process each line or token.
5
Close the Scanner when done to release the file resource.

Example: Counting Lines

// Count the number of lines in a file Scanner sc = new Scanner(new File("poem.txt")); int count = 0; while (sc.hasNextLine()) { sc.nextLine(); // read and discard count++; } sc.close(); System.out.println("Lines: " + count);

Example: Summing Numbers

Given a file scores.txt with one integer per line, compute the total:

Scanner sc = new Scanner(new File("scores.txt")); int total = 0; while (sc.hasNextInt()) { total += sc.nextInt(); } sc.close(); System.out.println("Total: " + total);

Example: Parsing CSV Data

Given students.csv with lines like "Alice,95,88,72", extract names and compute averages:

while (sc.hasNextLine()) { String line = sc.nextLine(); String[] parts = line.split(","); String name = parts[0]; double sum = 0; for (int i = 1; i < parts.length; i++) { sum += Integer.parseInt(parts[i]); } double avg = sum / (parts.length - 1); System.out.println(name + ": " + avg); }

Read, Process, Write

// Read numbers, double them, write to new file Scanner in = new Scanner(new File("input.txt")); PrintWriter out = new PrintWriter("output.txt"); while (in.hasNextInt()) { int num = in.nextInt(); out.println(num * 2); } in.close(); out.close(); // Essential!

Key Scanner Methods

Method Returns Use Case
nextLine() String Read an entire line
next() String Read next whitespace-delimited token
nextInt() int Read and parse an integer
nextDouble() double Read and parse a decimal
hasNextLine() boolean Check if more lines exist
hasNextInt() boolean Check if next token is an int

Common Mistakes

✕ Forgetting close()
PrintWriter buffers output. Without close(), the file may be empty or incomplete.
✕ No try-catch
FileNotFoundException is checked: the code won't compile without handling it.
✕ Wrong file path
The file must be in the project root directory, not inside src/. Use an absolute path if unsure.
✕ Mixing nextLine() with nextInt()
After nextInt(), the newline stays in the buffer. A subsequent nextLine() reads an empty string.
✕ Reading past end of file
Calling nextLine() without checking hasNextLine() throws a NoSuchElementException.

Summary Table

Task Class Key Method Exception
Read text Scanner nextLine() FileNotFoundException
Read numbers Scanner nextInt() / nextDouble() FileNotFoundException
Write text PrintWriter println() / print() FileNotFoundException
Parse tokens String split(",") None (runtime errors)
Convert types Integer / Double parseInt() / parseDouble() NumberFormatException

Question 1 of 5

Which class is used to read from a text file in Java?

Question 2 of 5

What happens if you forget to call close() on a PrintWriter?

Question 3 of 5

What exception must be handled (or declared) for this code to compile?

Question 4 of 5

A file numbers.txt contains: 10 20 30 on one line. What does the following code print?

Question 5 of 5

What does String.split(",") return when called on the String "a,b,c"?