0

I have a program that will go through and create multiple different class instances. I want to write the details of each instance to a file using DataOutputStream (it's a necessary exercise, I'll look at other ways of doing this later), but the problem is I noticed that DataOutputStream overwrites the file each time a new instance is created and written. My first idea was each time a new instance is written, first using DataInputStream to get what's in the file, save it, and then rewrite it with the new instance. This seems like it could get confusing very fast. What would be best practice for something like this? Thanks in advance.

EDIT: I will try and be a bit more specific about what I'm trying to do here. When I take the class that I want to write to the file, first I'll use an dataInputStream.readFully to get everything in the file. My understanding is that takes all the bytes in the file and stores them in an array. I would like to compare this with the class instance and if the instance matches something already in the file, don't output this particular instance (because it's already there) to the file. Otherwise, append to the file.

Benny
  • 242
  • 1
  • 5
  • 17

1 Answers1

0

Use the FileOutputStream(File file, boolean append) constructor when you open the file for writing. For example:

File f = new File("C:\data.txt");
FileOutputStream fos = new FileOutputStream(f, true); // open file for appending
DataOutputStream dos = new DataOutputStream(fos);
// anything written to dos after this point will be appended

If you just need to serialize your objects, I'd highly recommend using JAXB or another serialization/marshaling API instead of reinventing the wheel. You'll potentially save a ton of time.

rob
  • 6,147
  • 2
  • 37
  • 56
  • I'm assuming this does no kind of checks for duplicates (just keeps growing the file)? I'll need to write something to get rid of dupes. – Benny May 01 '13 at 21:54
  • This purely appends to the very end of the existing file. If you have something else in mind, I'd suggest editing your question or asking a new question, including a more detailed explanation of the expected or desired behavior (pseudocode or code will also help). However, you may also want to investigate JAXB or JavaBeans Serialization or another similar API, since they have already solved the root problem that you're trying to solve (serializing data to disk). – rob May 01 '13 at 22:32
  • I would totally use serialization but, it's a specific exercise I'm trying to work through. I've edited the question to try and explain better. thanks – Benny May 01 '13 at 22:50