Java – How To Read file and save data to ArrayList

we have to save ArrayList of names to a text file called “names.txt” in the previous article, Now in this article, we will read that file and save that saved data/items to ArrayList again


import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class Main {

     * @param file_name
     * @param list
    public static void read(String file_name, ArrayList<String> list) {
        try {
            File myObj = new File(file_name);
            try (Scanner myReader = new Scanner(myObj)) {
                while (myReader.hasNextLine()) {
                    String data = myReader.nextLine();
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");

    public static void main(String[] args)
            throws FileNotFoundException, IOException, ClassNotFoundException {
        ArrayList<String> names = new ArrayList<>();
        read("names.txt", names);



READ ALSO: Java – How To Write / Save ArrayList to a file