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

后端 未结 6 1486
时光取名叫无心
时光取名叫无心 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:50

    To save and load an arraylist of public static ArrayList data = new ArrayList ();

    I used (to write)...

    static void saveDatabase() {
    try {
    
            FileOutputStream fos = new FileOutputStream("mydb.fil");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(data);
            oos.close();
            databaseIsSaved = true;         
    
        }
    catch (IOException e) {
            e.printStackTrace();
    }
    
    } // End of saveDatabase
    

    And used (to read) ...

    static void loadDatabase() {
    
    try {           
            FileInputStream fis = new FileInputStream("mydb.fil");
            ObjectInputStream ois = new ObjectInputStream(fis);         
            data = (ArrayList)ois.readObject();
            ois.close();            
        }       
    catch (IOException e) {
            System.out.println("***catch ERROR***");
            e.printStackTrace();
    
        }       
    catch (ClassNotFoundException e) {
            System.out.println("***catch ERROR***");
            e.printStackTrace();
        }   
    } // End of loadDatabase 
    

提交回复
热议问题