I want to read a text file containing space separated values. Values are integers. How can I read it and put it in an array list?
Here is an example of contents of the text file:
1 62 4 55 5 6 77
I want to have it in an arraylist as [1, 62, 4, 55, 5, 6, 77]. How can I do it in Java?
[1, 62, 4, 55, 5, 6, 77]
You can use Files#readAllLines() to get all lines of a text file into a List<String>.
Files#readAllLines()
List<String>
for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) { // ... }
Tutorial: Basic I/O > File I/O > Reading, Writing and Creating text files
You can use String#split() to split a String in parts based on a regular expression.
String#split()
String
for (String part : line.split("\s+")) { // ... }
Tutorial: Numbers and Strings > Strings > Manipulating Characters in a String
You can use Integer#valueOf() to convert a String into an Integer.
Integer#valueOf()
Integer
Integer i = Integer.valueOf(part);
Tutorial: Numbers and Strings > Strings > Converting between Numbers and Strings
You can use List#add() to add an element to a List.
List#add()
List
numbers.add(i);
Tutorial: Interfaces > The List Interface
So, in a nutshell (assuming that the file doesn't have empty lines nor trailing/leading whitespace).
List<Integer> numbers = new ArrayList<>(); for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) { for (String part : line.split("\s+")) { Integer i = Integer.valueOf(part); numbers.add(i); } }
If you happen to be at Java 8 already, then you can even use Stream API for this, starting with Files#lines().
Files#lines()
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());
Tutorial: Processing data with Java 8 streams
1.4m articles
1.4m replys
5 comments
57.0k users