-2

In my java code I want to append massage objects to a file AT THE MOMENT THEY ARE BEING CREATED. When I try to append a new object it overwrites previously added data in the file. Can someone explain a method to append objects (not string type objects) one by one to a existing file without getting overwritten?

Constructor of the object:

public class savedEmail{

    String email;
    String subject;
    String date;
    public savedEmail(String email,String subject,String date){
        this.email = email;
        this.subject = subject;
        this.date = date;
    }
}

//The way which I tried to append the object to the file: 

class sentEmail{

    public static void save(saveEmail O) throws IOException{ObjectOutputStream op = new ObjectOutputStream(new
        FileOutputStream("saved.bin",true));

        op.write(0);
    }
}

2 Answers2

1

The way that I figured out to solve this was, putting all the objects into an ArrayList and writing that ArrayList into a file by object serialization. If you want to add a new object to it, take the saved ArrayList back by deseriazing it, then append the new object and put the ArrayList back to the file.

0

When you create a new ObjectOutputStream, an initial sequence of bytes, or header, is written. The Java Serialization Specification describes it:

stream:

magic version contents

So, creating a new ObjectOutputStream each time you want to append is not an option. You will need to open a single ObjectOuptutStream, and keep a reference to it.

By the way, op.write(0) (writing a zero) is not the same as op.write(O) (writing the object whose reference is in the variable whose name is the capital letter O). This is one reason O is a very poor choice for a variable name. Consider naming the method argument email instead.

VGR
  • 40,506
  • 4
  • 48
  • 63