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
.
Simplest form I ever found is...
Add this code to sort the data in text file.
Collections.sort(list);
In Java 8 you could use streams and
Files.lines
:Or as a function including loading the file from the file system:
Here is an entire program example:
To share some analysis info. With a simple test how long it takes to read ~1180 lines of values.
If you need to read the data very fast, use the good old BufferedReader FileReader example. It took me ~8ms
The Scanner is much slower. Took me ~138ms
The nice Java 8 Files.lines(...) is the slowest version. Took me ~388ms.