Java reading a file into an ArrayList?

This Java code reads in each word and puts it into the ArrayList:

Scanner s = new Scanner(new File("filepath"));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()){
    list.add(s.next());
}
s.close();

Use s.hasNextLine() and s.nextLine() if you want to read in line by line instead of word by word.

Leave a Comment