Sunday, January 14, 2024

How to read a text file into ArrayList in Java? Examples

Prior to Java 7, reading a text file into an ArrayList involves a lot of boilerplate coding, as you need to read the file line by line and insert each line into an ArrayList, but from Java 7 onward, you can use the utility method Files.readAllLines() to read all lines of a text file into a List. This method returns a List of String that contains all lines of files. Later you can convert this List to ArrayList, LinkedList, or whatever list you want to. Btw, this the fourth article in the series of reading a text file in Java. 

In the earlier parts, you have learned how to read a file using Scanner and BufferedReader(1). Then, reading the whole file as String (2) and finally reading a text file into an array (3). This program is not very different from those in terms of fundamentals. 

We are still going to use the read() method for Java 6 solution and will read all text until this method returns -1 which signals the end of the file.



Reading text file into ArrayList in Java - BufferedReader Example

If you know how to read a file line by line, either by using Scanner or by using BufferedReader then reading a text file into ArrayList is not difficult for you. All you need to do is read each line and store that into ArrayList, as shown in the following example:

    BufferedReader bufReader = new BufferedReader(new FileReader("file.txt"));
    ArrayList<String> listOfLines = new ArrayList<>();

    String line = bufReader.readLine();
    while (line != null) {
      listOfLines.add(line);
      line = bufReader.readLine();
    }

    bufReader.close();

Just remember to close the BufferedReader once you are done to prevent resource leak, as you don't have a try-with-resource statement in Java 6.




Reading text file into List in Java - Files.readAllLines Example

In Java 7, you don't need to write code to read and store into ArrayList, just call the Files.readAllLines() method and this will return you a list of String, where each element is the corresponding line from the line. Since List is an ordered collection the order of lines in a file is preserved in the list. 

You can later convert this List to ArrayList or any other implementation.

here is sample code to read text file into List in JDK 7:

public static List<String> readFileIntoList(String file) {
    List<String> lines = Collections.emptyList();
    try {
      lines = Files.readAllLines(Paths.get(file), StandardCharsets.UTF_8);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return lines;
  }

The readAllLines() method accepts a CharSet, you can use a pre-defined character set e.g. StandardCharsets.UTF_8 or StandardCharsets.UTF_16.  You can also see these free Java Courses to learn more about new file utility classes introduced in Java 7 and 8.




Java Program to read text file into ArrayList

Here is the complete Java program to demonstrate both methods to read a text file into ArrayList. This program first teaches you how to do this in JDK 7 or Java 8 using the Files.readAllLines() method and later using BufferedReader and ArrayList in Java 6 and lower version.

You can compile and run this program from the command prompt or if you want to run in Eclipse, just copy and paste in Eclipse Java project. The Eclipse IDE will automatically create a source file for you. 

Then just right-click and Run as Java Program. Make sure you have file.txt in your classpath. Since I have given the relative path here, make sure you put that file inside the Eclipse project directory.

How to read text file into List in Java - example



Reading text file into ArrayList in Java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/*
 * Java Program read a text file into ArrayList in Java 6
 * and Java 8. 
 */

public class ReadFileIntoArrayList {

  public static void main(String[] args) throws Exception {

    // reading text file into List in Java 7
    List<String> lines = Collections.emptyList();
    try {
      lines = Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    System.out.println("Content of List:");
    System.out.println(lines);

    // reading text file into ArrayList in Java 6
    BufferedReader bufReader = new BufferedReader(new FileReader("file.txt"));
    ArrayList<String> listOfLines = new ArrayList<>();

    String line = bufReader.readLine();
    while (line != null) {
      listOfLines.add(line);
      line = bufReader.readLine();
    }

    bufReader.close();
    System.out.println("Content of ArrayLiList:");
    System.out.println(listOfLines);

  }

}


Output
Content of List:
[Python, Ruby, JavaScript]
Content of ArrayLiList:
[Python, Ruby, JavaScript]



That's all about how to read a text file into ArrayList in Java. You can see it's very easy in Java 7 and Java 8 by using Files.readAllLines() method. Though you should be mindful of character encoding while reading a text file in Java.

 In Java 6 also, the solution using BufferedReader or Scanner is not very difficult to implement, but the thing you need to remember is that you are loading the whole file into memory. 

If the file is too big and you don't have enough memory, your program will die by throwing java.lang.OutOfMemoryError: Java Heap Space. In short, this solution is only good for a small files, for the large files you should always read by streaming.

5 comments:

  1. How to read text file line by line in Java and use the data to make condition. for example do {
    // Statements
    }while(Boolean_expression);

    for the below text data

    ID: 0 predicted: anomaly
    ID: 1 predicted: anomaly
    ID: 2 predicted: normal
    ID: 3 predicted: anomaly
    ID: 4 predicted: anomaly
    ID: 5 predicted: normal
    ID: 6 predicted: normal
    ID: 7 predicted: normal
    ID: 8 predicted: normal
    ID: 9 predicted: normal
    ID: 10 predicted: normal

    ReplyDelete
  2. how to read names and integers from file and put it in different arrays in java

    ReplyDelete
  3. how to read the text file (list of students(ID,Name,Course,Class)) into array in java

    ReplyDelete
    Replies
    1. If its a CSV File with a header then you can use Jackson to load that file as shown in the example here - How to load CSV file with header in Java

      Delete

Feel free to comment, ask questions if you have any doubt.