Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java reading a file into an ArrayList?

Tags:

java

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.

like image 567
user618712 Avatar asked Mar 17 '11 18:03

user618712


People also ask

How do you read a file into an ArrayList?

All you need to do is read each line and store that into ArrayList, as shown in the following example: BufferedReader bufReader = new BufferedReader(new FileReader("file. txt")); ArrayList<String> listOfLines = new ArrayList<>(); String line = bufReader. readLine(); while (line !

How do you add a file to 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.

How do you read data from a file and store it in an array in Java?

In Java, we can store the content of the file into an array either by reading the file using a scanner or bufferedReader or FileReader or by using readAllLines method.


1 Answers

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.

like image 177
Ahmed Kotb Avatar answered Sep 22 '22 17:09

Ahmed Kotb