Java

How to Read a Text File and Store it in an Array in Java

Java allows us to read a file using different methods and put the file’s contents into an array. As you may have no idea about the exact number of lines or words in a file, it is better to utilize the collection storage type to store the file’s content rather than a static array. This array can be used to process its lines or only for reading purposes.

This article will describe the methods to read a text file in Java and store it in an array.

How to Read a Text File and Store it in an Array?

There are four methods for reading the contents of a file, such as:

  • The Scanner class
  • The BufferedReader class
  • The readAllLines() method
  • The FileReader class

Note: For the demonstration purpose, first, we will create a text file named “Javafile.txt” that contains the following text:

LearnJava
LinuxHint

Now, we will discuss the most commonly used Java methods for the mentioned purpose.

Method 1: Read a Text File and Store it in an Array Using Scanner class

In Java, the “Scanner” class belongs to java.util package used to read data from users for primitive data types. It can also be used to read content from a file. To load content from a file, Scanner is used in combination with File or FileReader.

Let’s check out an example to understand the usage of Scanner for reading a text file and storing it in an array.

Example
In this example, first, we will create a String type ArrayList named “stngFile” to store the text content of a file:

List<String> stngFile = new ArrayList<String>();

Then, we will load the text of our “Javafile.txt” by creating a new object of Scanner class and pass the file path as an argument:

Scanner scnr = new Scanner(new FileReader(
              "C:\\Users\\Mughal's\\Desktop\\Java\\Javafile.txt"));

As a condition of the “while” loop, use “hasnext()” method to verify whether there are any strings left in the file or not. In its body, the created scanner object will read the file text and store it in the ArrayList “stngFile”:

String str;
while (scnr.hasNext()) {
            str = scnr.next();
            stngFile.add(str);
        }

After getting all of all file text in ArrayList, convert it to array by using “toArray()” method:

Lastly, print the values stored in the array using the for-each” loop:

for(String eachString : array) {
            System.out.println(eachString);
        }

The given output indicates that we have successfully read a text file using Scanner class object and stored its content in an array:

Look at the below-given section to utilize BufferedReader class for reading a text file.

Method 2: Read a Text File and Store it in an Array Using BufferedReader Class

BufferedReader” is another Java class used to read and load the file content in combination with the FileReader. Character files are read using the FileReader class. It performs a read operation on every character in the file. To read and load content from a file using the BufferedReader class is significantly faster as compared to other methods.

Example
First, we will create an object of the BufferedReader class by passing the file path to it:

BufferedReader bfredr = new BufferedReader(new FileReader
                 ("C:\\Users\\Mughal's\\Desktop\\Java\\Javafile.txt"));

The “bfredr” object will read a line from the specified file using “readLine()” method and store it in “text” String type variable:

String text= bfredr.readLine();

Next, add a “while” loop that executes until the value of the “text” variable becomes “null”. Within the body, we will add the current value of the text variable to the “stngFile” ArrayList and update its value according to the next line’s content:

while (text != null) {
      stngFile.add(text);
      text = bfredr.readLine();
   }
  bfredr.close();

Then, convert the created ArrayList to an array by using the “toArray()” method:

String[] array = stngFile.toArray(new String[0]);

Finally, we will print the text values stored in the array with the help of the “for-each” loop:

 for (String eachstring : array) {
      System.out.println(eachstring);
}

Output

We presented the information related to reading a text file and storing it in an array in Java.

Conclusion

To read a text file and store it in an array, Java provides many methods such as Scanner, BufferedReader, and FileReader classes and the readAllLines() method. However, Java programmers prefer Scanner and BufferReader classes because the BufferedReader object is faster, and the Scanner object is best for analyzing text data. In this article, we described the methods to read a text file and store it in an array in Java in detail.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.