Reading a File into ArrayList in Java

Learn to read all the lines from a file into ArrayList using Java IO APIs, Common IO and Guava classes.

Remember that reading the whole file into memory is recommended only for small text files where we may want to refer to the file content multiple times in the program. In such cases, reading the file multiple times is not an ideal solution. So we must read the file content once in the List, and then refer to it in all the other places in the program.

1. Reading All Lines into ArrayList

To read all the lines from the file, we have multiple efficient solutions that require only a single statement execution. Let us see a few of them.

1.1. Java NIO’s Files.readAllLines()

The readAllLines() method reads all lines from a file. It also closes the file when all bytes have been read or an I/O error, or other runtime exception, is thrown.

try {
  List<String> list = Files.readAllLines(
      new File("data.txt").toPath(), Charsets.UTF_8 );
} catch (IOException e) {
  e.printStackTrace();
}

1.2. Java NIO’s Files.lines()

Many times, we may want to process the lines as they are read. In such cases, we can read the file as Stream and apply some intermediate actions on the stream elements as they are processed.

try (Stream<String> stream = Files.lines(Paths.get("data.txt"))) {
  ArrayList<String> arrayList = stream
      .collect(Collectors.toCollection(ArrayList::new));
}
catch (IOException e) {
  e.printStackTrace();
}

1.3. Common IO’s FileUtils.readLines()

This method also reads the contents of a file line by line to a List of Strings. The file is always closed after the read operation is finished.

try {
  List<String> lines = FileUtils.readLines(
      new File("data.txt"), StandardCharsets.UTF_8);
} catch (IOException e) {
  e.printStackTrace();
}

1.4. Guava’s Files.readLines()

This method returns a mutable list of strings that contains all the lines from the file.

For an ImmutableList, use Files.asCharSource(file, charset).readLines().

try {
  List<String> lines = com.google.common.io.Files.readLines(
      new File("data.txt"), StandardCharsets.UTF_8);
} catch (IOException e) {
  e.printStackTrace();
}

2. Reading File Line by Line and Collect into List

Another way to read all lines in the file is, to read the file one line at a time in a while loop and add it to the List.

This solution presents us the opportunity to perform necessary data sanitization before adding to the list. We can also choose to include or discard the line.

2.1. Using Scanner

The Scanner is a simple text scanner, used for parsing primitive types and strings, using regular expressions.

We can use the nextLine() method to read an entire line. To check if there is more content in the file, we can use the hasNext() method.

try(Scanner s = new Scanner(new File("data.txt"))) {
  ArrayList<String> list = new ArrayList<>();
  while (s.hasNext()) {
    list.add(s.next());
  }
} catch (FileNotFoundException e) {
  e.printStackTrace();
}

2.2. Using BufferedReader

The BufferedReader class also provides methods, similar to the Scanner class, that can be used to read the line and check for any remaining content in the file.

try (BufferedReader reader = new BufferedReader(
    new FileReader("data.txt"))) {
  ArrayList<String> list = new ArrayList<>();
  while (reader.ready()) {
    list.add(reader.readLine());
  }
}
catch (IOException e) {
  e.printStackTrace();
}

3. Conclusion

As shown in the discussed solutions, reading all the lines from a file is not a complex problem to solve. We can decide the solution based on the requirements if there is some intermediate processing required before adding the line to the List or not.

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode