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?
You can use
Files#readAllLines()to get all lines of a text file into aList<String>.Tutorial: Basic I/O > File I/O > Reading, Writing and Creating text files
You can use
String#split()to split aStringin parts based on a regular expression.Tutorial: Numbers and Strings > Strings > Manipulating Characters in a String
You can use
Integer#valueOf()to convert aStringinto anInteger.Tutorial: Numbers and Strings > Strings > Converting between Numbers and Strings
You can use
List#add()to add an element to aList.Tutorial: Interfaces > The List Interface
So, in a nutshell (assuming that the file doesn’t have empty lines nor trailing/leading whitespace).
If you happen to be at Java 8 already, then you can even use Stream API for this, starting with
Files#lines().Tutorial: Processing data with Java 8 streams