Home > Java > javaTutorial > How to Load a File\'s Contents into a Java ArrayList?

How to Load a File\'s Contents into a Java ArrayList?

Susan Sarandon
Release: 2024-12-16 14:29:16
Original
558 people have browsed it

How to Load a File's Contents into a Java ArrayList?

How to Populate an ArrayList with Data from a File in Java

This question explores the process of reading the contents of a file into an ArrayList of strings in Java. The provided file contains various words, and the goal is to store each word as an element in the ArrayList.

To achieve this, the following Java code can be used:

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

This code utilizes the Scanner class to read from the file. The Scanner object is initialized using the new File("filepath") constructor, where "filepath" represents the path to the target file.

Once the Scanner object is created, the hasNext() method checks if there are more words in the file. If there are, the next() method is called to retrieve the next word and add it to the ArrayList using list.add(). This process continues until the end of the file is reached.

Finally, the s.close() method is called to close the Scanner object and release any associated resources.

If the aim is to read the file line by line instead of word by word, the code can be modified to use s.hasNextLine() and s.nextLine() instead of s.hasNext() and s.next().

The above is the detailed content of How to Load a File\'s Contents into a Java ArrayList?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template