All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

How To Read A File In Java

Last Updated : Mar 11, 2024

How To Read A File In Java

In this article we will show you the solution of how to read a file in java, the java.io package contains classes that are used to read files in Java. Streams are used for file input/output (I/O) operations, allowing for quick data flow between programmes and files.

Both the java.io.FileReader and java.io.Java typically uses BufferedReader classes to read text files.

It takes a methodical process to read a file in Java, which includes opening the file, reading its contents, and then appropriately closing the file to free up system resources.

You may read files of any size quickly and handle the data as needed by using strategies like exception handling, buffering, as well as iteration.

Now let's talk about the idea of reading files in Java.

Step By Step Guide On How To Read A File In Java :-

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileReadingExample {
    public static void main(String[] args) {
        String fileName = "example.txt"; // Replace with your file name or path
        try (FileReader fileReader = new FileReader(fileName);
             BufferedReader bufferedReader = new BufferedReader(fileReader)) {
            String line;
            int lineCount = 0;
            int wordCount = 0;
            int characterCount = 0;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
                // Counting lines
                lineCount++;
                // Counting words
                String[] words = line.split("\\s+");
                wordCount += words.length;
                // Counting characters
                characterCount += line.length();
            }
            System.out.println("Total lines: " + lineCount);
            System.out.println("Total words: " + wordCount);
            System.out.println("Total characters: " + characterCount);
        } catch (IOException e) {
            System.out.println("An error happened when reading the file.: " + e.getMessage());
        }
    }
}
  1. The Java code that demonstrates how to read a file in Java is written here, as you can see.
  2. In order to get started, we import the BufferedReader, FileReader, and IOException classes from the java.io package.
  3. We must take these lessons in order to read files and manage any potential I/O issues.
  4. A class called FileReadingExample is defined.
  5. We declare and initialize the String variable fileName with the value "example.txt" inside the main procedure.
  6. The path or file name of the file we wish to read is represented by this variable.
  7. We can change it to the required path or file name.
  8. A try-with-resources block is reached.
  9. Even if an exception occurs, this block makes sure that the resources being used (FileReader & BufferedReader) are appropriately closed after use.
  10. Within the try statement's parenthesis, we declare and initialize the resources.
  11. We define and set the values of three variables that are integers (lineCount, wordCount, and characterCount) to 0 within the try block.
  12. The number of lines, words, and characters in the file will be recorded using these variables.
  13. The readLine() function of the BufferedReader class is used to start a while loop that reads each line from the file one by one.
  14. If there are still lines to read (line!= null), the loop will keep going.
  15. Using System.out.println(line), we print each line to the console while in the loop.
  16. The lineCount variable is then raised by 1, counting the current line.
  17. We use the split("s+") method to divide the line into an array of words so that we may count the words in it.
  18. The line is divided into words by the regular expression "s+," which matches any number of whitespace characters.
  19. We increase the wordCount by the length of the resulting array.
  20. To keep track of the overall number of characters in the file, we add the length of the current line to characterCount.
  21. Using the while loop, we use System.out.println() to print the total number of lines, words, and characters to the console.
  22. The block for the catch is activated in the event that an exception arises while reading the file.
  23. An IOException is caught, and a message of error indicating a problem with the file reading is displayed.

Conclusion :-

As a result, we have successfully acquired the knowledge necessary to read a file in Java.

We also discovered that we can effectively read files and obtain their information by using classes like BufferedReader and FileReader.

We also looked at how to use try-with-resources to make sure that resources are managed properly and that exceptions are handled.

I hope this article on how to read a file in java helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Riya

A recent graduate with a Bachelor of Technology (B.Tech) in Computer Science from India. She is passionate about leveraging technology to solve real-world problems. With a strong foundation and experience in programming languages such as Python, Django, HTML, CSS, and JavaScript, java, php and have honed her skills through hands-on projects and coursework.

Follow Riya On Linkedin 🡪