codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
☕

Java Programming

45 / 65 topics
43Java Files44Java Create & Write Files45Java Read Files46Java Delete Files47Java I/O Streams48FileInputStream & FileOutputStream49BufferedReader & BufferedWriter
Tutorials/Java Programming/Java Read Files
☕Java Programming

Java Read Files

Updated 2026-05-12
15 min read

Java Read Files

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.

Introduction

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:

  • Using the Scanner class to read text files
  • Handling FileNotFoundException to manage missing files gracefully
  • Best practices for file handling

Reading Files with Scanner

The 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.

Basic File Reading Example

Let's start with a simple example where we read a text file line by line using the Scanner class.

ReadFileExample.java
1import java.io.File;
2import java.io.FileNotFoundException;
3import java.util.Scanner;
4
5public class ReadFileExample {
6 public static void main(String[] args) {
7 try {
8 File file = new File("example.txt");
9 Scanner scanner = new Scanner(file);
10
11 while (scanner.hasNextLine()) {
12 String line = scanner.nextLine();
13 System.out.println(line);
14 };
15
16 scanner.close();
17 } catch (FileNotFoundException e) {
18 System.out.println("File not found: " + e.getMessage());
19 }
20 }
21}

Explanation

  1. Import Statements: We import necessary classes from the java.io package.
  2. File Object: We create a File object representing the file we want to read (example.txt).
  3. Scanner Object: We create a Scanner object to read from the file. This throws a FileNotFoundException if the file does not exist.
  4. Reading Lines: We use a while loop with scanner.hasNextLine() to check if there are more lines to read. The nextLine() method reads each line and prints it.
  5. Close Scanner: It's important to close the Scanner object using scanner.close() to free up resources.

Handling FileNotFoundException

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.

Terminal
$ javac ReadFileExample.java
$ java ReadFileExample
File not found: example.txt

OutputBlock

Output
File not found: example.txt

Reading Specific Data Types

The Scanner class provides methods to read different data types directly from the file. Here's an example of reading integers and doubles.

ReadNumericData.java
1import java.io.File;
2import java.io.FileNotFoundException;
3import java.util.Scanner;
4
5public class ReadNumericData {
6 public static void main(String[] args) {
7 try {
8 File file = new File("numbers.txt");
9 Scanner scanner = new Scanner(file);
10
11 while (scanner.hasNext()) {
12 if (scanner.hasNextInt()) {
13 int number = scanner.nextInt();
14 System.out.println("Integer: " + number);
15 } else if (scanner.hasNextDouble()) {
16 double number = scanner.nextDouble();
17 System.out.println("Double: " + number);
18 }
19 }
20
21 scanner.close();
22 } catch (FileNotFoundException e) {
23 System.out.println("File not found: " + e.getMessage());
24 }
25 }
26}

Explanation

  1. Reading Integers and Doubles: We use scanner.hasNextInt() and scanner.hasNextDouble() to check the type of data before reading it.
  2. Output: The program prints each integer or double read from the file.

Best Practices for File Handling

  • Always Close Resources: Use a try-with-resources statement to ensure that resources like Scanner are closed automatically.
ReadFileWithTryWithResources.java
1import java.io.File;
2import java.io.FileNotFoundException;
3import java.util.Scanner;
4
5public class ReadFileWithTryWithResources {
6 public static void main(String[] args) {
7 File file = new File("example.txt");
8 try (Scanner scanner = new Scanner(file)) {
9 while (scanner.hasNextLine()) {
10 String line = scanner.nextLine();
11 System.out.println(line);
12 }
13 } catch (FileNotFoundException e) {
14 System.out.println("File not found: " + e.getMessage());
15 }
16 }
17}
  • Use Absolute Paths: When working with file paths, using absolute paths can help avoid issues related to relative path resolution.

Practical Example

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.

StudentGrades.java
1import java.io.File;
2import java.io.FileNotFoundException;
3import java.util.Scanner;
4
5public class StudentGrades {
6 public static void main(String[] args) {
7 File file = new File("grades.txt");
8 try (Scanner scanner = new Scanner(file)) {
9 int totalGrades = 0;
10 int count = 0;
11
12 while (scanner.hasNextDouble()) {
13 double grade = scanner.nextDouble();
14 totalGrades += grade;
15 count++;
16 }
17
18 if (count > 0) {
19 double averageGrade = (double) totalGrades / count;
20 System.out.println("Average Grade: " + averageGrade);
21 } else {
22 System.out.println("No grades found.");
23 }
24 } catch (FileNotFoundException e) {
25 System.out.println("File not found: " + e.getMessage());
26 }
27 }
28}

Explanation

  1. Reading Grades: The program reads each grade from the file and calculates the total.
  2. Calculating Average: After reading all grades, it calculates and prints the average grade.

Summary

  • Use the Scanner class to read text files in Java.
  • Handle FileNotFoundException to manage missing files gracefully.
  • Best practices include closing resources properly and using absolute paths for file operations.
ConceptDescription
Scanner ClassUsed for reading input from various sources, including files.
FileNotFoundExceptionThrown when a file is not found. Handle it using try-catch blocks.
Try-with-resourcesEnsures that resources are closed automatically, preventing resource leaks.

What's Next?

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!


PreviousJava Create & Write FilesNext Java Delete Files

Recommended Gear

Java Create & Write FilesJava Delete Files