How to serialize ArrayList 2x and dont over write the already present ArrayList JAVA

ぃ、小莉子 提交于 2020-01-03 05:11:28

问题


I'm stuck with making an admin panel for my program to serialize more objects, what it does is , it saves object(String,String) into arraylist and the arraylist is saved into file through serialization.

When trying to add another object into the arraylist, The program first deserialize the file stuff into the arraylist, because by not doing this how would i access the objects that are already present in the file.?

but instead something like this happens while adding object 3

(console)

Index 0 [[Word : word1 - Hint : hint1], Word : word2 - Hint : hint2]

how to solve this ?

I think i should delete the old arraylist every time a new a new object is created but i dont know how to do that, is there anything i can do to edit the old arraylist in the file instead of deleting it. Thanks in advance

enter code here
class Admin{
ArrayList al = new ArrayList();
public void ifwordsarepresent(){

try {
    FileInputStream fis = new FileInputStream("D:/serial.txt");
    ObjectInputStream ois = new ObjectInputStream(fis);

if(fis.available()>0){
try {
    try {

       al.add((ArrayList) ois.readObject());
       addingwords();
       ois.close();

    } catch

public void addingwords(){
    try {
    try {
    System.out.print("New Word = ");
    Scanner scan = new Scanner(System.in);
    String word = scan.next();

    System.out.print("New hint = ");
    Scanner scan2 = new Scanner(System.in);
    String hint = scan2.nextLine();

    FileOutputStream fos = new FileOutputStream("D:/serial.txt");        
    ObjectOutputStream oos = new ObjectOutputStream(fos);


    Word newword = new Word(word , hint);
    al.add(newword);

    oos.writeObject(al);
    oos.flush();
    oos.close();
    }catch (FileNotFoundException e) {          
        e.printStackTrace();
    }}catch(IOException e) {
          System.out.println("Exception during serialization: " + e);
              }   

    MovingForward();

    }

来源:https://stackoverflow.com/questions/23044159/how-to-serialize-arraylist-2x-and-dont-over-write-the-already-present-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!