Java IoT Authors: Elizabeth White, Liz McMillan, Yeshim Deniz, Pat Romanski, Zakia Bouachraoui

Related Topics: Java IoT

Java IoT: Article

The Data Series: Object Serialization

The Data Series: Object Serialization

Data is one of those housekeeping duties that has to be performed by everyone who uses a computer. Whatever level they are on, somewhere along the line data is stored, files are created and directories are made.

Last month I introduced the whole notion of data and suggested ways in which we might handle various quantities of the stuff. One of the greatest problems faced by the developer is that of storage. Every situation seems to call for a different solution. For example, last month we looked at storing small amounts of data through the use of INI, or program information files. A complete class for this type of manipulation was developed and by the time implementation was complete we had a class that allowed the storing and retrieval of data arranged in key/value pairs.

In this column we will look at the saving and loading of complete classes through the use of the Object Serialization mechanism introduced in the 1.1 version of the JDK.

"Our object in the construction of the state is the greatest happiness of the whole, and not that of any one class."

These words were uttered by Plato around 400 B.C., and it makes you wonder just how old this supposedly new object-orientation really is. While we ponder this in the back of our minds, let's have a look at Object Serialization.

Object Serialization
In a nutshell, Object Serialization is a mechanism that allows an object to be represented as a byte stream. This byte stream can then be passed on to any of the Java streams, such as sockets and files, and then reassembled back into the original object with no data loss. Using this technique, not only can objects be safely saved and restored, but they can also be passed onto other machines in a distributed environment. In fact, Remote Method Invocation, or RMI, uses serialization in exactly this manner.

At this point you may be thinking that it sounds a little complicated. More hassle than it's really worth. Be prepared to be pleasantly surprised. Object Serialization has been made so easy to use, there's really no excuse for not taking advantage of it. Let's look at an example.

Listing 1 shows the saving of both a String and a Date object. You will notice the first thing that is created is an instance to an OutputStream. In this instance we are using a FileOutputStream, but this could have been any output stream. Next we create an ObjectOutputStream instance, which is what we will use to write the data to the output stream. Writing the actual objects out to disk is then a simple matter of calling the writeObject( ) method for each object that is to be saved.

The ObjectOutput interface is part of the java.io package. Listing 2 shows the main methods for this interface, of which ObjectOutputStream is an implementation.

As seen in Listing 2, the most important method is writeObject(...), which takes as a parameter a reference to an Object which can be transposed to a stream of bytes.

Recreating the objects is as simple as writing them in the first place. For each output-orientated method/class, the equivalent input methods exist. For example, to read back in the objects we wrote out earlier, we can use the code shown in Listing 3.

Instead of using writeObject(...), we use readObject(...), casting the objects necessary. One important point must be made, and that is the order in which objects are read and written. Generally, they have to be read in the same order they were written out in. This ensures the correct data is associated with each object.

The majority of the classes in JDK1.1 can be read and written using this technique. For example, let's say you had a Hashtable and it was populated with hundreds of String objects. Writing this out to disk can be performed using one call to writeObject(...) with the hash table as the object reference passed in. This will write out all the data associated with the hash table, including all the String objects. This is one of the greatest features of object serialization, the ability to present the developer with an interface that makes the saving and retrieval of objects a really trivial matter.

If the majority of the classes in the JDK are already for serialization, how do you go about making your own classes serializable? This is a very easy thing to do. Simply have your class implement the java.io.Serializable interface. Listing 4 illustrates this.

That's it! It's as simple as that. Once your class implements this interface, it can be read and saved as easily as the examples earlier in this article.

This article took a look at the Object Serialization method that was introduced in the 1.1 release of the JDK. As was demonstrated, reading and writing of object data is made extremely easy. But this isn't limited to just saving data in files. The same technique can be used to send complete objects to processes running on other machines via Sockets.

In next month's article we will look at JDBC and how we can start reading and writing volumes of data stored in an external database.

More Stories By Alan Williamson

Alan Williamson is widely recognized as an early expert on Cloud Computing, he is Co-Founder of aw2.0 Ltd, a software company specializing in deploying software solutions within Cloud networks. Alan is a Sun Java Champion and creator of OpenBlueDragon (an open source Java CFML runtime engine). With many books, articles and speaking engagements under his belt, Alan likes to talk passionately about what can be done TODAY and not get caught up in the marketing hype of TOMORROW. Follow his blog, http://alan.blog-city.com/ or e-mail him at cloud(at)alanwilliamson.org.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

IoT & Smart Cities Stories
DXWorldEXPO LLC announced today that ICOHOLDER named "Media Sponsor" of Miami Blockchain Event by FinTechEXPO. ICOHOLDER gives detailed information and help the community to invest in the trusty projects. Miami Blockchain Event by FinTechEXPO has opened its Call for Papers. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Miami Blockchain Event by FinTechEXPOalso offers sp...
Headquartered in Plainsboro, NJ, Synametrics Technologies has provided IT professionals and computer systems developers since 1997. Based on the success of their initial product offerings (WinSQL and DeltaCopy), the company continues to create and hone innovative products that help its customers get more from their computer applications, databases and infrastructure. To date, over one million users around the world have chosen Synametrics solutions to help power their accelerated business or per...
DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.
@DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22nd international CloudEXPO | first international DXWorldEXPO and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time t...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...
Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
Machine learning has taken residence at our cities' cores and now we can finally have "smart cities." Cities are a collection of buildings made to provide the structure and safety necessary for people to function, create and survive. Buildings are a pool of ever-changing performance data from large automated systems such as heating and cooling to the people that live and work within them. Through machine learning, buildings can optimize performance, reduce costs, and improve occupant comfort by ...
SYS-CON Events announced today that IoT Global Network has been named “Media Sponsor” of SYS-CON's @ThingsExpo, which will take place on June 6–8, 2017, at the Javits Center in New York City, NY. The IoT Global Network is a platform where you can connect with industry experts and network across the IoT community to build the successful IoT business of the future.
CloudEXPO New York 2018, colocated with DXWorldEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.