Reading a File into an ArrayList in Java
When working with text data, it's often useful to store it in a data structure for easy manipulation and processing. In Java, an ArrayList is a commonly used collection for holding a list of objects, including strings. This article demonstrates how to read the contents of a file into an ArrayList of strings.
File Preparation
First, ensure you have a text file with line-separated data, as shown in the provided example:
cat house dog ...
Java Code to Read the File
To read the contents of the file into an ArrayList of strings, use the following code:
import java.util.ArrayList; import java.util.Scanner; import java.io.File; public class FileToList { public static void main(String[] args) { try { // Create a Scanner object for the file Scanner s = new Scanner(new File("filepath")); // Create an ArrayList to store the words ArrayList<String> list = new ArrayList<>(); // Loop through the file and add each word to the ArrayList while (s.hasNext()) { list.add(s.next()); } // Close the Scanner s.close(); // Print the ArrayList to the console System.out.println(list); } catch (Exception e) { e.printStackTrace(); } } }
Explanation
Alternative for Reading Line by Line
If you prefer to read the file line by line instead of word by word, modify the code as follows:
... // Loop through the file and add each line to the ArrayList while (s.hasNextLine()) { list.add(s.nextLine()); } ...
In this case, s.hasNextLine() checks for the presence of a new line, and s.nextLine() retrieves the entire line.
The above is the detailed content of How to Read a File into an ArrayList in Java?. For more information, please follow other related articles on the PHP Chinese website!