Reading files is a fundamental task in programming, allowing your Java applications to access data stored on disk. This tutorial will guide you through reading text files using the Scanner class and handling potential exceptions like FileNotFoundException. Understanding these concepts is crucial for developing robust file-handling capabilities in your Java programs.
In the previous topic, we learned how to create and write files in Java. Now, let's focus on reading those files. Reading files enables your application to retrieve data from storage, which can be used for processing, analysis, or display. This tutorial will cover:
Scanner class to read text filesFileNotFoundException to manage missing files gracefullyThe Scanner class in Java is a convenient tool for reading input from various sources, including files. It provides methods to read different types of data such as integers, doubles, and strings.
Let's start with a simple example where we read a text file line by line using the Scanner class.
1import java.io.File;2import java.io.FileNotFoundException;3import java.util.Scanner;45public class ReadFileExample {6public static void main(String[] args) {7try {8File file = new File("example.txt");9Scanner scanner = new Scanner(file);1011while (scanner.hasNextLine()) {12String line = scanner.nextLine();13System.out.println(line);14};1516scanner.close();17} catch (FileNotFoundException e) {18System.out.println("File not found: " + e.getMessage());19}20}21}
java.io package.File object representing the file we want to read (example.txt).Scanner object to read from the file. This throws a FileNotFoundException if the file does not exist.while loop with scanner.hasNextLine() to check if there are more lines to read. The nextLine() method reads each line and prints it.Scanner object using scanner.close() to free up resources.In the example above, we handle the FileNotFoundException using a try-catch block. This ensures that if the file is not found, our program can respond gracefully by printing an error message instead of crashing.
$ javac ReadFileExample.java$ java ReadFileExampleFile not found: example.txt
File not found: example.txt
The Scanner class provides methods to read different data types directly from the file. Here's an example of reading integers and doubles.
1import java.io.File;2import java.io.FileNotFoundException;3import java.util.Scanner;45public class ReadNumericData {6public static void main(String[] args) {7try {8File file = new File("numbers.txt");9Scanner scanner = new Scanner(file);1011while (scanner.hasNext()) {12if (scanner.hasNextInt()) {13int number = scanner.nextInt();14System.out.println("Integer: " + number);15} else if (scanner.hasNextDouble()) {16double number = scanner.nextDouble();17System.out.println("Double: " + number);18}19}2021scanner.close();22} catch (FileNotFoundException e) {23System.out.println("File not found: " + e.getMessage());24}25}26}
scanner.hasNextInt() and scanner.hasNextDouble() to check the type of data before reading it.try-with-resources statement to ensure that resources like Scanner are closed automatically.1import java.io.File;2import java.io.FileNotFoundException;3import java.util.Scanner;45public class ReadFileWithTryWithResources {6public static void main(String[] args) {7File file = new File("example.txt");8try (Scanner scanner = new Scanner(file)) {9while (scanner.hasNextLine()) {10String line = scanner.nextLine();11System.out.println(line);12}13} catch (FileNotFoundException e) {14System.out.println("File not found: " + e.getMessage());15}16}17}
Let's create a complete example that reads a text file containing student names and their grades. The program will read the data and calculate the average grade.
1import java.io.File;2import java.io.FileNotFoundException;3import java.util.Scanner;45public class StudentGrades {6public static void main(String[] args) {7File file = new File("grades.txt");8try (Scanner scanner = new Scanner(file)) {9int totalGrades = 0;10int count = 0;1112while (scanner.hasNextDouble()) {13double grade = scanner.nextDouble();14totalGrades += grade;15count++;16}1718if (count > 0) {19double averageGrade = (double) totalGrades / count;20System.out.println("Average Grade: " + averageGrade);21} else {22System.out.println("No grades found.");23}24} catch (FileNotFoundException e) {25System.out.println("File not found: " + e.getMessage());26}27}28}
Scanner class to read text files in Java.FileNotFoundException to manage missing files gracefully.| Concept | Description |
|---|---|
| Scanner Class | Used for reading input from various sources, including files. |
| FileNotFoundException | Thrown when a file is not found. Handle it using try-catch blocks. |
| Try-with-resources | Ensures that resources are closed automatically, preventing resource leaks. |
In the next topic, we will learn how to delete files in Java. Understanding how to create, read, and delete files is essential for building applications that manage data storage effectively.
Stay tuned for more tutorials on file handling and I/O streams!