How to read a plain text file in java? | Projectshop

Sure, here’s a step-by-step guide along with code for reading a plain text file in Java:

1. Import necessary packages: Import the required classes from the ‘java.io package, which provides classes for input and output operations.

Java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

2. Create a BufferedReader object: BufferedReader is used to read text from a character-input stream efficiently.

Java
BufferedReader reader = null;

3. Specify the file path: Provide the path to the text file you want to read.

Java
String filePath = "path/to/your/file.txt";

4. Open the file: Create a FileReader object and pass the file path to its constructor

Java
try {
    reader = new BufferedReader(new FileReader(filePath));
} catch (IOException e) {
    e.printStackTrace();
}

5. Read the file line by line: Use the ‘readLine()‘ method of BufferedReader to read each line from the file until it returns null, indicating the end of the file

Java
try {
    String line;
    while ((line = reader.readLine()) != null) {
        // Process each line here
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if (reader != null) {
            reader.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

6. Close the BufferedReader: It’s important to close the BufferedReader after you finish reading the file to release system resources.

That’s it! This code will read each line from the specified text file and print it to the console. You can modify the code inside the ‘while‘ loop to process each line according to your requirements.

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Cart