2

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

Code

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();
                    list.add(data);
                }
            }
        } 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);
        System.out.println(names);

    }

}

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

shaad

2 Comments

  1. Excellent site. Lots of useful info here. I’m sending
    it to some buddies ans also sharing in delicious. And of course, thanks for your sweat!

Leave a Reply

Your email address will not be published. Required fields are marked *