1

Java – How To Write / Save ArrayList to a file

Suppose we have ArrayList of some type of data and we want to save that ArrayList to file and need that data for later use. Today I will tell you how to save ArrayList to file, so let get started and save the ArrayList to a text file.

we have ArrayList named names of type String and we are goint to save all items in ArrayList to file,so below is the code of saving ArrayList data/items to a text file

Code

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;

public class Main {

    public static void save(String file_name,
            ArrayList<String> names) throws FileNotFoundException {
        PrintWriter pw = new PrintWriter(new FileOutputStream(file_name));
        for (String name : names) {
            pw.println(name);
        }
        pw.close();
    }

    public static void main(String[] args) throws FileNotFoundException {
        ArrayList<String> names = new ArrayList<>();
        names.add("John");
        names.add("Sam");
        names.add("Smith");
        names.add("Harry");
        save("names.txt", names);
        System.out.println("Array List save to file names.txt");

    }

}

After running the above code all names are saved in file “names.txt”, and we can read that file in the next part

READ ALSO: Java – How To Read file and save data to ArrayList

shaad

One Comment

Leave a Reply

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