Home > Java > javaTutorial > How to Read a Text File into an ArrayList in Java?

How to Read a Text File into an ArrayList in Java?

Linda Hamilton
Release: 2024-12-11 05:59:09
Original
623 people have browsed it

How to Read a Text File into an ArrayList in Java?

Java: Read a Text File into an Array List

Introduction

Reading a text file into an array list in Java is a common programming task. This article demonstrates how to achieve this, covering techniques that leverage the Files, String, Integer, and List classes.

Reading the File

To read the file, use the Files#readAllLines() method to obtain a list of its lines. Each line represents a row in the text file.

List<String> lines = Files.readAllLines(Paths.get("/path/to/file.txt"));
Copy after login

Splitting the Lines

Since the values in the file are separated by spaces, use the String#split() method to break each line into individual values:

for (String line : lines) {
    String[] values = line.split("\s+");
}
Copy after login

Converting Strings to Integers

As the values in the text file are integers, convert them to Integer objects using Integer#valueOf():

for (String value : values) {
    Integer i = Integer.valueOf(value);
}
Copy after login

Adding to Array List

Create an array list and add the converted integers to it using the List#add() method:

List<Integer> numbers = new ArrayList<>();
numbers.add(i);
Copy after login

Combining the Steps

Combining these steps, you can read the file and populate the array list in one go:

List<Integer> numbers = new ArrayList<>();
for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
    for (String value : line.split("\s+")) {
        Integer i = Integer.valueOf(value);
        numbers.add(i);
    }
}
Copy after login

Java 8 Stream API

In Java 8, you can simplify the process using the Stream API:

List<Integer> numbers = Files.lines(Paths.get("/path/to/test.txt"))
    .map(line -> line.split("\s+")).flatMap(Arrays::stream)
    .map(Integer::valueOf)
    .collect(Collectors.toList());
Copy after login

The above is the detailed content of How to Read a Text File into an ArrayList in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template