Home > Java > javaTutorial > How Can I Efficiently Read a File into an ArrayList in Java?

How Can I Efficiently Read a File into an ArrayList in Java?

Patricia Arquette
Release: 2024-12-10 16:56:14
Original
866 people have browsed it

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();
Copy after login

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()
Copy after login

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
Copy after login

The above code will populate the ArrayList with the strings:

["cat", "house", "dog"]
Copy after login

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!

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