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"));
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+"); }
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); }
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);
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); } }
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());
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!