简体   繁体   English

使用ObjectOutputStream自动覆盖对象

[英]auto overwrite object with ObjectOutputStream

When i save a second object, and the first one is deleted from the file, how can i solve this? 当我保存第二个对象,并且第一个对象从文件中删除时,我该如何解决?

public void guardar(){ 
    try {
        ObjectOutputStream oos = new ObjectOutputStream(new 
        FileOutputStream("Datos.obj"));
        Object O[] = new Object[5];
        O[0] = getRfc();
        O[1] = getNombre();
        O[2] = getEdad();
        O[3] = getPuesto();
        O[4] = getSalario();
        oos.writeObject(O);
        oos.flush();
        oos.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(datos.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(datos.class.getName()).log(Level.SEVERE, null, ex);
    }   
}

Thanks in advance if someone can help me. 在此先感谢您能帮助我。

You will need to read the file with the first object array. 您将需要使用第一个对象数组读取文件。 Then create a java.util.ArrayList of object arrays and save first the first object array into it, then the second object into it and then serialize the list containing these two object arrays. 然后创建一个对象数组的java.util.ArrayList ,然后将第一个对象数组保存到其中,然后将第二个对象保存到其中,然后序列化包含这两个对象数组的列表。

If you have a third object to serialize you have to again read the java.util.ArrayList from the file and append to it the third object and so on. 如果您要序列化第三个对象,则必须再次从文件中读取java.util.ArrayList并将其附加到第三个对象,依此类推。

Just a note: it is better to initially save the first object array into a java.util.ArrayList even though you have only one single object array. 请注意:最好最初将第一个对象数组保存到java.util.ArrayList即使您只有一个对象数组也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM