Home >Java >javaTutorial >How Can I Efficiently Read a File into an ArrayList in Java?
Efficiently Reading File Contents into an ArrayList in Java
Reading the contents of a file into an ArrayList in Java can be a useful task for handling text-based data. To achieve this, we can utilize the Scanner class.
Reading Data Word by Word:
To read the file contents word by word, the following code snippet can be employed:
Scanner s = new Scanner(new File("filepath")); ArrayList<String> list = new ArrayList<>(); while (s.hasNext()){ list.add(s.next()); } s.close();
Reading Data Line by Line:
If you wish to read the file contents line by line, simply modify the Scanner methods as follows:
s.hasNextLine() s.nextLine()
With this approach, each line of the file will be added as an element to the ArrayList.
Example:
Consider a file with the following contents:
cat house dog
The above code will populate the ArrayList with the strings:
["cat", "house", "dog"]
Note:
Remember to close the Scanner object using s.close() to release system resources once you have finished reading the file.
The above is the detailed content of How Can I Efficiently Read a File into an ArrayList in Java?. For more information, please follow other related articles on the PHP Chinese website!