Java read text file using java.io.BufferedReader
Another way to read a text file in Java is by using the java.io.BufferedReader class.
For example:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileExample {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this example, we create a `BufferedReader` object by passing a `FileReader` instance to its constructor. The `FileReader` is initialized with the path to the file we want to read.
We use a `try-with-resources` statement to automatically close the `BufferedReader` after we're done reading the file. Inside the `try` block, we use a `while` loop to read the file line by line using the `readLine()` method. We continue reading until `readLine()` returns `null`, indicating that we've reached the end of the file.
For each line read, we simply print it to the console using `System.out.println()`. If any exception occurs during the file reading process, it will be caught & printed by the `catch` block.
Using `BufferedReader` is efficient for reading large files as it reads the file in chunks, reducing the number of I/O operations & improving performance.
Using Scanner to read text file in Java
The `Scanner` class in Java provides a convenient way to read text files. Here's an example of how to use `Scanner` to read a file:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFileExample {
public static void main(String[] args) {
try {
// Create a File object representing the file to read
File file = new File("file.txt");
// Create a Scanner object to read the file
Scanner scanner = new Scanner(file);
// Read the file line by line
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
// Close the Scanner
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
In this example, we create a `File` object representing the file we want to read. Then, we create a `Scanner` object by passing the `File` object to its constructor.
We use a `while` loop to read the file line by line. The `hasNextLine()` method of the `Scanner` class checks if there is another line to read. If there is, we use the `nextLine()` method to read the line & store it in the `line` variable. We then print each line to the console using `System.out.println()`.
After we've finished reading the file, we close the `Scanner` using the `close()` method to release any resources associated with it.
If the specified file is not found, a `FileNotFoundException` will be thrown, which we catch & print the stack trace.
Using `Scanner` is a simple & straightforward way to read text files in Java, especially when you need to process the file line by line.
Java Read File Example
Let’s see an example that shows reading a file in Java using the `java.nio.file.Files` class:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class ReadFileExample {
public static void main(String[] args) {
try {
// Specify the path to the file
Path path = Paths.get("example.txt");
// Read the contents of the file into a List of Strings
List<String> lines = Files.readAllLines(path);
// Print the contents of the file
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Assuming we have a file named "example.txt" with the following content:
Hello, World!
This is an example file.
It contains multiple lines of text.
When we run the `ReadFileExample` program, it will output:
Hello, World!
This is an example file.
It contains multiple lines of text.
In this example, we use the `Paths.get()` method to specify the path to the file we want to read. Then, we use the `Files.readAllLines()` method to read the contents of the file into a `List` of `String` objects, where each element in the list represents a line from the file.
Finally, we use a `for-each` loop to iterate over the lines in the list & print each line to the console using `System.out.println()`.
The `Files.readAllLines()` method reads the entire file into memory at once & returns a `List` of `String` objects. It's suitable for small to medium-sized files. If the file is very large, you might consider using other methods like `Files.lines()` to read the file line by line in a memory-efficient way.
Frequently Asked Questions
What happens if the file is not found when using java.nio.file.Files?
If the file is not found, a NoSuchFileException will be thrown, which is a subclass of IOException. You can catch this exception & handle it appropriately in your code.
Can we read binary files using the same methods as text files?
Yes, you can read binary files using the Files.readAllBytes() method or by using InputStream classes like FileInputStream. However, for reading text files, it's recommended to use character-based classes like BufferedReader or Scanner.
Is there a way to read a file line by line without loading the entire file into memory?
Yes, you can use the Files.lines() method or the BufferedReader class to read a file line by line. These approaches allow you to process the file in a memory-efficient manner, especially for large files.
Conclusion
In this article, we learned about different ways to read files in Java. We started using the java.nio.file.Files class, java.io.BufferedReader, & Scanner class to read text files. We also saw a complete example of reading a file using Files.readAllLines(). Java provides flexible & efficient methods for reading files, allowing us to choose the approach that best suits our needs based on the file size & memory constraints.
You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.