0% completed
Reading files is a fundamental part of file handling in Java. It involves opening a file, reading its contents, and then processing or displaying the data. Java provides several classes in the java.io
and java.nio
packages to handle file reading. In this lesson, we focus on the traditional I/O approach using classes like FileReader
and BufferedReader
to read text files.
Below is a table that summarizes key concepts and classes used in reading files:
Concept/Class | Description |
---|---|
FileReader | A class for reading character files. It reads data one character at a time from a file. |
BufferedReader | Wraps a FileReader to efficiently read text from a file in large chunks (lines) instead of single characters. |
Scanner | A versatile class that can parse primitive types and strings using regular expressions. It can also read from files. |
Try-With-Resources | A statement that ensures each resource is closed at the end of the statement, simplifying the cleanup of file handles. |
FileReader
object that points to the file you want to read.FileReader
in a BufferedReader
to read lines efficiently.readLine()
method in a loop to read the file line by line.IOException
, so proper exception handling is necessary.In this example, we demonstrate how to read a text file named "input.txt" line by line using BufferedReader
and try-with-resources. The code will display each line in the console.
Example Explanation:
FileReader
is created for "input.txt"
and wrapped inside a BufferedReader
to improve efficiency.readLine()
method reads each line until it returns null
, indicating the end of the file.IOException
that may occur during file reading.BufferedReader
when the block is exited.In this example, we use the Scanner
class to read the contents of "input.txt" line by line. The code prints each line to the console.
Example Explanation:
File
object is instantiated to represent "input.txt"
.Scanner
is used to read the file, with hasNextLine()
and nextLine()
iterating through each line.Scanner
is closed, and a catch block handles the FileNotFoundException
.Reading files in Java is accomplished by using classes such as FileReader
, BufferedReader
, and Scanner
. These classes allow you to open a file, read its content line by line, and handle any potential I/O errors gracefully. The examples provided demonstrate two common approaches:
.....
.....
.....