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

后端 未结 6 1502
时光取名叫无心
时光取名叫无心 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条回答
  •  忘掉有多难
    2020-11-27 15:42

    You should use Java's built in serialization mechanism. To use it, you need to do the following:

    1. Declare the Club class as implementing Serializable:

      public class Club implements Serializable {
          ...
      }
      

      This tells the JVM that the class can be serialized to a stream. You don't have to implement any method, since this is a marker interface.

    2. To write your list to a file do the following:

      FileOutputStream fos = new FileOutputStream("t.tmp");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(clubs);
      oos.close();
      
    3. To read the list from a file, do the following:

      FileInputStream fis = new FileInputStream("t.tmp");
      ObjectInputStream ois = new ObjectInputStream(fis);
      List clubs = (List) ois.readObject();
      ois.close();
      

提交回复
热议问题