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.
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.
Why Use Text Files?
The Java I/O Pipeline
Reading with Scanner
Writing with PrintWriter
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
Step-by-Step: Reading a File
Example: Counting Lines
Example: Summing Numbers
Given a file scores.txt with one integer per line, compute the total:
Example: Parsing CSV Data
Given students.csv with lines like "Alice,95,88,72", extract names and compute averages:
Read, Process, Write
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
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
Consider the following code:
Scanner sc = new Scanner(new File("data.txt"));
while (sc.hasNextLine()) {
String line = sc.nextLine();
System.out.println(line.toUpperCase());
}
sc.close();
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"?