Java Program To Read A Text File And Display Its Contents
Reading and displaying the contents of a text file is a common and essential task in Java programming. Whether for configuration, data processing, or logging, knowing how to interact with files efficiently is crucial. In this article, you will learn how to read a text file and print its contents to the console using several robust Java approaches.
Problem Statement
Many applications require processing external data stored in text files. The core problem is to open a specified file, read its content (typically line by line), and then display that content, often to the standard output (console). This task necessitates handling potential issues like the file not existing or errors during reading, ensuring the program runs reliably.
Example
Consider a simple text file named sample.txt with the following content:
Hello from the file!
This is the second line.
Java file I/O is powerful.
The desired output of our program would be to print each line of this file exactly as it appears:
Hello from the file!
This is the second line.
Java file I/O is powerful.
Background & Knowledge Prerequisites
To effectively understand the solutions presented, readers should have a basic understanding of:
- Java Fundamentals: Variables, loops (
while,for), conditional statements (if-else). - Exception Handling:
try-catchblocks, as file operations are prone toIOExceptionandFileNotFoundException. - Basic I/O Concepts: Input/Output streams, the idea of reading from a source.
Before running the code examples:
Ensure you have a text file (e.g., sample.txt) in the same directory as your Java program, or provide the full path to the file. For instance, create a file named sample.txt with some content.
Use Cases or Case Studies
Reading text files is a foundational skill with numerous practical applications:
- Configuration Files: Applications often read
.propertiesor.jsonfiles to load settings and parameters. - Log Analysis: Tools can parse application log files (e.g.,
.logfiles) to extract error messages, performance data, or user activity. - Data Processing: Reading
.csvor other delimited text files to import data into a program for analysis, transformation, or storage. - Content Display: Displaying help documentation, license agreements, or other textual information stored in simple text files.
- Text Manipulation: Performing operations like word counting, search and replace, or spell checking on text documents.
Solution Approaches
Here are three common and effective approaches to read a text file in Java and display its contents, including best practices like try-with-resources for automatic resource management.
Approach 1: Using java.util.Scanner
One-line summary: A simple and convenient way to read text data, token by token or line by line.
The Scanner class is part of the java.util package and is excellent for parsing primitive types and strings using regular expressions. When reading files, it can be wrapped around a File object to read its content easily, line by line.
// Read File with Scanner
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
String fileName = "sample.txt"; // Ensure this file exists in the same directory
// Step 1: Use try-with-resources to ensure the Scanner is closed automatically
try (Scanner scanner = new Scanner(new File(fileName))) {
// Step 2: Loop while there are more lines to read
while (scanner.hasNextLine()) {
// Step 3: Read the next line and print it to the console
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
// Step 4: Handle the case where the file does not exist
System.err.println("Error: The file '" + fileName + "' was not found. " + e.getMessage());
}
}
}
Sample Output:
Assuming sample.txt contains:
Hello from the file!
This is the second line.
Java file I/O is powerful.
The output will be:
Hello from the file!
This is the second line.
Java file I/O is powerful.
Stepwise Explanation:
- Define File Name: A
StringvariablefileNamestores the name of the file to be read. try-with-resourcesBlock: AScannerobject is created to read from the specifiedFile. This is wrapped in atry-with-resourcesstatement, which guarantees that thescannerresource will be closed automatically once thetryblock finishes, even if exceptions occur.- Looping Through Lines:
scanner.hasNextLine()checks if there's another line of text available. If true,scanner.nextLine()reads and returns that line. - Printing Lines:
System.out.println()prints each read line to the console. - Error Handling: The
catch (FileNotFoundException e)block handles the specific case where the file specified byfileNamedoes not exist, printing an informative error message.
Approach 2: Using java.io.BufferedReader
One-line summary: An efficient way to read text, especially larger files, by buffering characters.
BufferedReader is more efficient for reading large files because it buffers input characters, reading a larger chunk at a time rather than character by character. It is typically chained with a FileReader.
// Read File with BufferedReader
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
String fileName = "sample.txt"; // Ensure this file exists
// Step 1: Use try-with-resources for BufferedReader
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
// Step 2: Read lines one by one until the end of the file (null)
while ((line = reader.readLine()) != null) {
// Step 3: Print each line to the console
System.out.println(line);
}
} catch (IOException e) {
// Step 4: Handle potential I/O errors (e.g., file not found, read errors)
System.err.println("Error reading the file '" + fileName + "': " + e.getMessage());
}
}
}
Sample Output:
Assuming sample.txt contains:
Hello from the file!
This is the second line.
Java file I/O is powerful.
The output will be:
Hello from the file!
This is the second line.
Java file I/O is powerful.
Stepwise Explanation:
- Define File Name: Same as before,
fileNameholds the path to the text file. try-with-resourcesBlock: ABufferedReaderis created, wrapping aFileReaderthat specifies the file to read. This setup ensures bothBufferedReaderandFileReaderare closed automatically.- Reading Lines in Loop: The
while ((line = reader.readLine()) != null)loop continuously reads lines from the file.reader.readLine()reads a single line of text. It returnsnullwhen the end of the file has been reached. The read line is assigned to thelinevariable. - Printing Lines:
System.out.println(line)prints each line to the console. - Error Handling: The
catch (IOException e)block handles any input/output errors that might occur during file operations, includingFileNotFoundException(which is a subclass ofIOException).
Approach 3: Using java.nio.file.Files.readAllLines()
One-line summary: A modern, concise approach for reading all lines of a file into a List.
Introduced in Java 7, the java.nio.file.Files class (NIO.2 API) provides convenient static methods for file operations. readAllLines() is particularly useful when you need to read the entire content of a text file into memory as a list of strings.
// Read File with Files.readAllLines
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
String fileName = "sample.txt"; // Ensure this file exists
Path filePath = Paths.get(fileName); // Step 1: Get a Path object for the file
try {
// Step 2: Read all lines from the file into a List of Strings
List<String> lines = Files.readAllLines(filePath);
// Step 3: Iterate through the list and print each line
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
// Step 4: Handle I/O errors
System.err.println("Error reading the file '" + fileName + "': " + e.getMessage());
}
}
}
Sample Output:
Assuming sample.txt contains:
Hello from the file!
This is the second line.
Java file I/O is powerful.
The output will be:
Hello from the file!
This is the second line.
Java file I/O is powerful.
Stepwise Explanation:
- Get
PathObject:Paths.get(fileName)converts the file name string into aPathobject, which is used by thejava.nio.fileAPI. - Read All Lines:
Files.readAllLines(filePath)reads every line from the specified file and returns them as aList. Each element in the list represents one line from the file. This method automatically handles opening and closing the file. - Iterate and Print: A simple
for-eachloop iterates through theListand prints each line to the console. - Error Handling: A
catch (IOException e)block handles any potential input/output errors during the file reading process.
Conclusion
Reading text files in Java can be accomplished using several effective methods, each with its advantages. The Scanner class is great for simplicity and parsing, BufferedReader offers efficiency for larger files, and Files.readAllLines() provides a modern, concise solution for reading entire files into memory. For robust applications, always remember to handle IOException and use try-with-resources to ensure file resources are properly closed, preventing resource leaks.
Summary
-
Scanner: Simple for line-by-line reading; ideal for beginners or when simple parsing is needed. -
BufferedReader: Efficient for large files due to buffering; preferred for performance-critical scenarios. -
Files.readAllLines(): Modern and concise, reads entire file into aList; best for smaller files where memory usage is not a concern. - Error Handling: Essential for file operations; use
try-catchblocks forIOExceptionorFileNotFoundException. - Resource Management: Always use
try-with-resourcesto automatically close file streams and prevent resource leaks.