DEV Community

Lalit Kumar
Lalit Kumar

Posted on

How to read a file into an array Java

In this article, I am going to explain how to read a file into an array java.

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 that is from Java 7 onward, you can use the utility method Files. readAllLines() to read all lines of the text file into a List. This method returns a List of String which contains all lines of files.


title: "How to read a file into an array java"
tags: java

canonical_url: https://kodlogs.com/blog/2294/how-to-read-a-file-into-an-array-java

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,

(1) you have learned how to read a file using Scanner and BufferedReader.

(2) Then, reading the whole file as String.

(3) and finally reading a text file into array.

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, by using Scanner or by using BufferedReader then reading a text file into ArrayList is not difficult for you. All you want 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();
Enter fullscreen mode Exit fullscreen mode

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

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. Later, you can 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;

  }
Enter fullscreen mode Exit fullscreen mode

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

Here is the complete Java program to demonstrate both of these methods to read a text file into ArrayList. This program first teaches 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);

  }


}
Enter fullscreen mode Exit fullscreen mode

Output


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

Top comments (0)