Java provides several ways to read data from a text file. We can use classes such as Scanner, FileReader, and BufferedReader to read file contents.
Reading a file means retrieving the data stored inside it.
For example, suppose message.txt contains:
Hello Java!
Welcome to file handling.
Our Java program can read and display this text on the screen.
The Scanner class can read text from a file.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try {
File file = new File("message.txt");
Scanner reader = new Scanner(file);
while (reader.hasNextLine()) {
String line = reader.nextLine();
System.out.println(line);
}
reader.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
}
}
}
File represents the file to read.Scanner reads data from the file.hasNextLine() checks whether another line exists.nextLine() reads the next line.close() closes the scanner.Consider a file named students.txt with this content:
Rahul
Amit
Priya
Neha
Java program:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try (Scanner reader =
new Scanner(new File("students.txt"))) {
while (reader.hasNextLine()) {
System.out.println(reader.nextLine());
}
} catch (FileNotFoundException e) {
System.out.println("Unable to find the file.");
}
}
}
Output:
Rahul
Amit
Priya
Neha
The try-with-resources statement closes the scanner automatically.
FileReader reads characters from a text file.
It is useful when you want to process characters directly.
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try (FileReader reader =
new FileReader("message.txt")) {
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
} catch (IOException e) {
System.out.println("Error reading file.");
}
}
}
The read() method returns the next character
as an integer, or -1 when the end of the file
is reached.
BufferedReader reads text efficiently and provides
the convenient readLine() method.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try (BufferedReader reader =
new BufferedReader(
new FileReader("message.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error reading file.");
}
}
}
Remember: readLine() returns
null when no more lines are available.
| Scanner | BufferedReader |
|---|---|
| Easy for beginners. | Useful for efficient text reading. |
Provides methods such as hasNextLine(). |
Provides the readLine() method. |
| Can parse values such as integers and doubles. | Reads text as characters or lines. |
| Can be convenient for simple programs. | Often preferred for reading lines efficiently. |
Modern Java provides the Files class for convenient
file operations. The following example reads an entire small
text file into a string.
import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
String content =
Files.readString(Path.of("message.txt"));
System.out.println(content);
} catch (IOException e) {
System.out.println("Unable to read file.");
}
}
}
Files.readString() is available in Java 11 and
later. It is suitable for small files that can fit comfortably
in memory.
You can read all lines of a text file into a
List<String> using Files.readAllLines().
import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;
import java.util.List;
public class Main {
public static void main(String[] args) {
try {
List<String> lines =
Files.readAllLines(Path.of("students.txt"));
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Unable to read file.");
}
}
}
This method loads all lines into memory, so avoid it for very large files. Use a buffered or streaming approach instead.
Suppose numbers.txt contains:
10
20
30
We can read each line and convert it to an integer:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try (Scanner reader =
new Scanner(new File("numbers.txt"))) {
int total = 0;
while (reader.hasNextLine()) {
String line = reader.nextLine().trim();
if (!line.isEmpty()) {
total += Integer.parseInt(line);
}
}
System.out.println("Total = " + total);
} catch (FileNotFoundException e) {
System.out.println("File not found.");
} catch (NumberFormatException e) {
System.out.println("The file contains invalid numbers.");
}
}
}
Output:
Total = 60
Integer.parseInt() converts numeric text into
an integer. Invalid numeric text causes a
NumberFormatException.
File reading can fail for several reasons:
Use exception handling to manage these problems:
try {
// File reading code goes here.
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
}
A relative path is resolved from the program's working directory.
File file = new File("message.txt");
An absolute path specifies the full file location.
File file = new File("C:/JavaFiles/message.txt");
The file must exist at the specified location, and the program must have permission to read it.
IOException and other relevant exceptions.BufferedReader for convenient line-by-line reading.Files.readString() for small text files when using Java 11 or later.hello.txt and display its contents.Scanner class.BufferedReader.FileReader and display each character.Files.readString().1. Which method reads the next line using BufferedReader?
2. What does Scanner.hasNextLine() check?
3. Which class provides Files.readString()?