How do you read the contents of a file into an ArrayList<String>
in Java?
Here are the file contents:
cat
house
dog
.
.
.
Just read each word into the ArrayList
.
How do you read the contents of a file into an ArrayList<String>
in Java?
Here are the file contents:
cat
house
dog
.
.
.
Just read each word into the ArrayList
.
Here's a solution that has worked pretty well for me:
If you don't want empty lines, you can also do:
You can use:
Source: Java API 7.0
This java code reads in each word and puts it into the ArrayList:
Use
s.hasNextLine()
ands.nextLine()
if you want to read in line by line instead of word by word.A one-liner with commons-io:
The same with guava:
You can for example do this in this way (full code with exceptions handlig):