Writing Objects to file in Java | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Writing Objects to file in Java

Recently I started learning about streams in Java and I can understand that there is a source where the information is held and it goes under some intermediate operations before reaching the terminal. But when I try to store or write an object of a particular class in a text file using the ObjectOutputStream then the representation of that object in the file is not understood though the output is correct when I try to again read and print it to the console. For eg- LocalDateTime class from java.time package or any other user defined class.

3rd Jan 2020, 9:19 AM
Avinesh
Avinesh - avatar
5 Answers
+ 2
it is a binary file, here's a little look at its structure https://www.javaworld.com/article/2072752/the-java-serialization-algorithm-revealed.html
3rd Jan 2020, 4:47 PM
zemiak
+ 2
zemiak I appreciate it, atleast someone replied to this question finally. It's just that I'm trying to play around learning new stuffs in Java. I just need some time to go through that link and will read it for sure. Thanks for your reply because even the java documentation doesn't explain that well.
3rd Jan 2020, 4:56 PM
Avinesh
Avinesh - avatar
+ 1
zemiak that was an interesting read, thanks! 👍 Avinesh I guess the point of serialization is that the object state is preserved and can be transmitted over a network etc. as a result of serialization.. It does not need to be human readable, just reconstructable from that specific format. In my mind this is similar of taking a snapshot like a save-game during playing, that you can reload later.
4th Jan 2020, 4:48 PM
Tibor Santa
Tibor Santa - avatar
+ 1
Tibor Santa I pretty much understood it but wanted to confirm it was actually true. Also I don't have to implement Serializable if I'm trying to store the current date and time to a file but since those are just simple numbers, I thought that they might me readable. But since even they are objects probably they are never meant to be formatted so that it is human readable because at the end of the day they have to be displayed on the console. Also thank you for your efforts to help me and by the way you have tagged someone else instead of me.
4th Jan 2020, 4:54 PM
Avinesh
Avinesh - avatar
+ 1
Sorry, tagging fixed, my mistake :)
4th Jan 2020, 5:11 PM
Tibor Santa
Tibor Santa - avatar