如何保存/加载ArrayList?

时间:2018-01-16 00:10:29

标签: java arrays arraylist

我正在尝试保存一个ArrayList(包含字符串)。 当我单击“保存”按钮时,它应该保存它,当我单击“加载”按钮时,它应该加载它。

我现在就有这个:

            aff.getButtonSave().addActionListener(new ActionListener(){ // aff = contains the display
        public void actionPerformed(ActionEvent event){
            //We check if we have at least one rule into the arraylist
            try {
                if(!rules.getListeRules().isEmpty()) {
                    PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));                   
                        pw.println(rules.toStringList()); //toStringList Returns a string of characters composed of each rule
                    } else {
                    writeHistorique("No rules found.."); //Writing inside the JScrollPane "Historique"
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        }
    });

对于保存一个,我也试过但是无法弄清楚..

亲切

1 个答案:

答案 0 :(得分:0)

A.Arthur,

你可能正在寻找这样的东西?

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class LoadSaveList {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add("Line " + i);
        }
        saveList(list);
        List<String> newList = new ArrayList<>();
        readList(newList);
        System.out.println(newList);
    }

    private static void readList(List<String> list) {
        try (BufferedReader br = new BufferedReader(new FileReader("output.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                list.add(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void saveList(List<String> list) {
        FileWriter writer = null;
        try {
            writer = new FileWriter("output.txt");
            for (String str : list) {
                writer.write(str + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}