Chapter 16. Saving Objects (and Text): Serialization and File I/O
Objects can be flattened and inflated. Objects have state and behavior. Behavior lives in the class, but state lives within each individual object. So what happens when itâs time to save the state of an object? If youâre writing a game, youâre gonna need a Save/Restore Game feature. If youâre writing an app that creates charts, youâre gonna need a Save/Open File feature. If your program needs to save state, you can do it the hard way, interrogating each object, then painstakingly writing the value of each instance variable to a file, in a format you create. Or, you can do it the easy OO wayâyou simply freeze-dry/flatten/persist/dehydrate the object itself, and reconstitute/inflate/restore/rehydrate it to get it back. But youâll still have to do it the hard way sometimes, especially when the file your app saves has to be read by some other non-Java application, so weâll look at both in this chapter. And since all I/O operations are risky, weâll take a look at how to do even better exceptions handling.
Capture the beat
Youâve made the perfect pattern. You want to save the pattern. You could grab a piece of paper and start scribbling it down, but instead you hit the Save button (or choose Save from the File menu). Then you give it a name, pick a directory, and exhale knowing that your masterpiece ...
Get Head First Java, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.