How to read a text file into ArrayList in Java

Prior to Java 7, reading a text file into an ArrayList involves lot of boiler plate 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 return a List of String which 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 array (3). This program is not very different from those in terms of fundamentals. We are still going to use read() method for Java 6 solution and will read all text until this method return -1 which signals the end of file.



Reading text file into ArrayList in Java 6

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 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 try-with-resource statement in Java 6.




Reading text file into List in Java 7

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 corresponding line from the line. Since List is an ordered collection the order of lines in file is preserved in 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.  See Core Java for the Impatient to learn more about new file utility classes introduced in Java 7 and 8.

How to read a text file into ArrayList in Java




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 teach you how to do this in JDK 7 or Java 8 using Files.readAllLines() method and later using BufferedReader and ArrayList in Java 6 and lower version. You can compile and run this program from command prompt or if you want to run in Eclipse, just copy and paste in Eclipse Java project. The Eclipse IDE will automatically create 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 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 its very easy in Java 7 and Java 8 by using Files.readAllLines() method. Though you should be mindful of character encoding while reading 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 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 small file, for large file you should always read by streaming.


No comments:

Post a Comment