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();
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!