This example will show how to read a text file into a java arraylist using java 7 nio, guava and apache commons. The text file referenced is used from the World Series Champions exercise program where it was necessary to read in a file and count the number of times a team won the world series based on user input.
Straight up Java
This snippet will provide an example using java 1.4 and above. We convert the Path to a file but you replace it with an existing file snippet. By creating a BufferedReader we are able to loop through the file by reading each line. If there is a line and it doesn't equal null we will add it to the teams list.
Java 7 File I/O
Using the Files utility class introduced in java 7 we will import all lines from the text file into an arraylist by calling readAllLines. This approach will make sure to close the file when the entire file has been read. This use approach will handle reading in small files so when reading in larger method alternative methods should be researched.
Java 8
Using java 8 we will use an equivalent approach to loading a file into an arraylist as above. We will use the Files utility class that will call lines which will read all lines of a file as a stream.
Google Guava
Using guava Files utility class we will read a entire file into an arrayList. Again, if you are reading large file alternative methods should be taken.
Apache Commons
Using apache commons FileUtils this snippet will read the content of the file line by line into an arraylist which uses the default encoding for the virtual machine. Once completed the file is always closed.