awareeye
awareeye

Reputation: 3061

How to replace content of a file in java?

I am writing data to a file using an ObjectOutputStream. I have a class Data which implements Serializable interface. This class has 4 instance variables. I am successfully able to write data to the file and also read it.

When the user changes any one of the instance variable of this class, I have to write all 4 variables to the file once again. Is there a solution to this such that instead of writing all four variable to the file, I just replace the data of the variable that has been changed?

Here is the some of the code:

public class Data implements Serializable{
     int i, j;
     String s1, s2;

}

Upvotes: 2

Views: 836

Answers (2)

Liv
Liv

Reputation: 6124

Rather than using Serializable you could look at Externalizable which would give you control over the way you write the serialized data -- so you could in fact if you want say serialize your object to CSV-like format. If you couple this with a diff mechanism (compare the line generated from the previous state the line that from the current state you could then use a RandomAccessFile and only write the differences.

Upvotes: 1

Bernd Elkemann
Bernd Elkemann

Reputation: 23550

If you are only serializing instances of your class you could just choose your own binary representation and implement methods to store/load objects. However, if you are using this "Data" class as part of e.g. Java-collections and gets serialized as part of those what you need is custom serialization, have a look here:

http://java.sun.com/developer/technicalArticles/Programming/serialization/

Under the heading:

Customize the Default Protocol

Upvotes: 0

Related Questions