Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList?

后端 未结 6 1500
时光取名叫无心
时光取名叫无心 2020-11-27 15:05

I am writing a program in Java which displays a range of afterschool clubs (E.G. Football, Hockey - entered by user). The clubs are added into the following ArrayList<

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 15:25

    As an exercise, I would suggest doing the following:

    public void save(String fileName) throws FileNotFoundException {
        PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
        for (Club club : clubs)
            pw.println(club.getName());
        pw.close();
    }
    

    This will write the name of each club on a new line in your file.

    Soccer
    Chess
    Football
    Volleyball
    ...
    

    I'll leave the loading to you. Hint: You wrote one line at a time, you can then read one line at a time.

    Every class in Java extends the Object class. As such you can override its methods. In this case, you should be interested by the toString() method. In your Club class, you can override it to print some message about the class in any format you'd like.

    public String toString() {
        return "Club:" + name;
    }
    

    You could then change the above code to:

    public void save(String fileName) throws FileNotFoundException {
        PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
        for (Club club : clubs)
             pw.println(club); // call toString() on club, like club.toString()
        pw.close();
    }
    

提交回复
热议问题