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?
Just for fun, here's what I'd probably do in a real project, where I'm already using all my favourite libraries (in this case Guava, formerly known as Google Collections).
Benefit: Not much own code to maintain (contrast with e.g. this). Edit: Although it is worth noting that in this case tschaible's Scanner solution doesn't have any more code!
Drawback: you obviously may not want to add new library dependencies just for this. (Then again, you'd be silly not to make use of Guava in your projects. ;-)
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 aString
in parts based on a regular expression.Tutorial: Numbers and Strings > Strings > Manipulating Characters in a String
You can use
Integer#valueOf()
to convert aString
into 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
Using Java 7 to read files with NIO.2
Import these packages:
This is the process to read a file:
To read all lines of a file at once:
Look at this example, and try to do your own:
read the file and then do whatever you want java8 Files.lines(Paths.get("c://lines.txt")).collect(Collectors.toList());
Java 1.5 introduced the Scanner class for handling input from file and streams.
It is used for getting integers from a file and would look something like this:
Check the API though. There are many more options for dealing with different types of input sources, differing delimiters, and differing data types.