-1

I recently learned about serialization and I am practicing it.I wanted to check if an object I'm about to serialize is already in the file or not.I think i can do this by looping through the file and check if it contains the object or not.But I cant found a way to loop through it.

Is there any way to loop through a serialized file or to check for contents ?

Sid
  • 465
  • 6
  • 14
  • why do you think you can loop through it ? if you think you can loop through it so it must be away? – Kick Buttowski Aug 25 '15 at 02:09
  • because it must be sorted in an order and if it does,i can loop through it right?? if not then it's ok.I also want to know if we can check if a content matches the object i'm about to enter.(I'm new so i'm still learning,also is there anyway to know how many object is stored inside the serialized file?) – Nguyễn Tuấn Aug 25 '15 at 02:16
  • `To serialize an object means to convert its state to a byte stream so that the byte stream can be reverted back into a copy of the object.` Check [here](https://docs.oracle.com/javase/tutorial/jndi/objects/serial.html) – Sid Aug 25 '15 at 02:23
  • @Sid Don't use code formatting for text that isn't code. – user207421 Aug 25 '15 at 07:21
  • @NguyễnTuấn What makes you think it is sorted? It isn't, unless you sorted it. – user207421 Aug 25 '15 at 07:22

1 Answers1

0

ObjectStream is not designed for it out of the box, but the exact solution depends on the size of your data + exact requirements.

1) If data is large, and business requirements are expected to evolve - I'd consider a proper database. E.g. mongodb if you'd like to write entire complex objects in one go (and, as the post implies, transactions are not required).

2) If you stick with ObjectOutputStream, then consider your exact file format - data retrieval would depend on that. However, all solutions boil down to loading the data to a java object in memory, and searching there...:

a) For small data, you could keep all data in a java List/Map (or some wrapper model object such as PhoneBook), then read/write it entirely in one go. E.g. on application startup: read the entire PhoneBook from file (or initialize an empty one if file is missing/corrupt). For search: search the PhoneBook object in memory. For update: update the PhoneBook object then write it entirely to file (in override mode). It goes without saying that one can add optimizations to the in-memory data structure, e.g. some HashMap to speed up the search.

b) There's an optimization to (a) which allows to append just one record at a time without re-writing the entire data, but it only works for append. Not for delete/update: Appending to an ObjectOutputStream

c) More advanced ideas are discussed in the following link, but IMHO it feels half way to writing your own database...: Object serialization and random access in java

Community
  • 1
  • 1
Pelit Mamani
  • 2,321
  • 2
  • 13
  • 11