Back to the Web Developer's Journal Main Page
internet.com
side nav bar

Object persistence - saving and restoring data - is a critical task for applications in any programming language. For writing Java applications or applets, serialization may just be the way to go.
Java Articles at the Web Developer's Journal - Java programming tutorials, applets, beans, servlets and more.
Back to the Web Developer's Journal Main Page
internet.com
side nav bar










We've tried to assemble a collection of articles about Java to help the beginner or the real Java gurus. If you have questions (or answers) concerning Java, please visit our Java Discussion Group.

HOW DID THEY DO THAT???

Find out in:
Amazing HTML



Site Map


Jobs at webdeveloper.com
Check out our Web-based
Discussion Groups:

Check out and join our email-based Mailing Lists for Web developers.

Ask the JavaScript Weenie:

For news and reviews of the latest computer audio tools, visit: The Tapeless Studio
Java Resources for Web Developers

Java Hub

If you have questions about Java development you have arrived at the right place. Scroll down for articles about servlets, product reviews and "how to do it" articles. We also maintain a Java discussion group.

 In This Section

 Java

  • Taking Notes on Java
    Edward Tanguay sings the praises of a very important language.

  • The Bluffer's Guide to Java
    Can't tell your Beans from your Applets? Wondering if a Servlet is a small server waiting to grow up? Read our compact guide to Java and you'll soon be dropping JAR, JVM and JSDK into casual conversations along with the best of them. Nobody will bother listening to you, but they'll still be mightily impressed.


  • Java: Coming to a TV near you!
    The new Java TV API holds the promise of Java-based interactive television using set-top boxes.


  • Java vs Other Web Application Technologies
    (The JavaBoutique) Selena Sol, author of JavaBoutique's Introduction to Java, gives an in-depth comparison of Java and other development languages such as dHTML, ASP, and Perl.
  • Agent Communication
    Agent technology is becoming more prevalent as the availability of network access, and the demand for the end-uses of agents, become greater.

  • Java Web Server in Brief
    A simple, dependable, and inexpensive ecommerce solution for small businesses is proposed.


  • JD WorkShop vs Cafe
    Two Java Tools Compared

 Java Server Pages

  • JSP: The Back Door into Java
    Edward Tanguay discovers JSP, and finds it finally allows him to put his theoretical knowledge of Java to use, and hence, get a foot into the Java programming world.

  • Building Java Server Pages
    A detailed look at building JSP pages. Should you use JSP or servlets? It depends on the ratio of markup to code. Here you'll also find a guide to the different varieties of tag, and details about the main tags such as <jsp:useBean> and <jsp:setProperty>.

  • Site User Logon with XML, Java Beans and JSP
    During this tutorial we will use XML and Java Server Pages to verify a user's logon - and then store the results in a session Java Bean for easy access.

  • Serving Dynamic WAP Content with Java Server Pages
    Here's how to create dynamic content for WAP-enabled mobile phones using the Wireless Markup Language (WML) and Sun Microsystems' Java Server API. Our Java Server Pages application displays regularly updated appointment data for someone on the move, such as an appliance engineer making house calls.

  • Object Persistence Made Easy
    With object serialization, your Java applets and applications can save and load the state of objects to disk or over a network. In this article, we'll examine the benefits of object serialization, and how to implement it in your own programs.

 Servlets

  • Intro to Servlets
    Java servlets are making headlines these days, claiming to solve many of the problems associated with CGI and proprietary server APIs. In this article I will describe the overall servlet architecture and what you need to develop your application with servlets. I will use several code examples to show you how to use the Servlet API, and compare it with CGI and proprietary server APIs where appropriate.

  • Internationalizing Servlets
    How to use the Java Internationalization API to build server-side code that alters its output based on the location and language of the user. We demonstrate the use of the API by building a simple method which displays a product entry for a shopping cart application.

  • Using the HttpSession object of the Servlet API
    The Java Servlet API represents an elegant and powerful way to shift processes from client to server, and offers a number of advantages over CGI. These advantages have certainly been enumerated so that most developers are aware of the servlet advantage. However, some of the details of the servlet architecture may at first seem daunting. Here's a short introduction on one aspect of writing servlets: the HttpSession object.

  • Improved Performance with a Connection Pool
    Establishing a connection once and then using the same connection for subsequent requests can dramatically improve the performance of a database-driven Web application. Since Servlets can keep information between requests, a database connection pool is a straightforward solution.

  • Servlets Are for Real!
    Servlets are on duty now at a Web site near you.

  • Netscape-Flavored Servlets
    How to implement server-side Java using Netscape's implementation of Java within the Enterprise Server.

 Java Discussion Group

  • Java Discussion Group
    Test the experts who hang out here with your toughest Java questions. You can also sign up for our Java E-mail Discussion List.
 

 

 Archive



Back to the Web Developer's Journal Contact WDJ   •    Suits!   •    Propheads!   •    Ponytails!
Discuss   •    Subscribe   •    Search

Be a Commerce Partner                       
HOW DID THEY DO THAT???

Find out in:
Amazing HTML



Site Map

Jobs at webdeveloper.com


Check out our Web-based
Discussion Groups:

Check out and join our email-based Mailing Lists for Web developers.


Developer Channel
FlashKit
Jobs.webdeveloper
JavaScript.com
JavaScriptSource
JustSMIL
ScriptSearch
Streaming Media World
WebDeveloper.com
WebReference
XMLFiles
WDVL
Discussion Groups Book Reviews Software Reviews Download Web Tools

Java Programming Tips

Object Persistence Made Easy

by David Reilly

With object serialization, your Java applets and applications can save and load the state of objects to disk or over a network. In this article, we'll examine the benefits of object serialization, and how to implement it in your own programs.
September 22, 1999

One of the most critical tasks that applications have to perform is to save and restore data. Whether it be a word processing application that saves documents to disk, a utility that remembers its configuration for next time, or a game that sets aside world domination for the night, the ability to store data and later retrieve it is a vital one. Without it, software would be little more effective that the typewriter - users would have to re-type the data to make further modifications once the application exits.

Writing the code for saving data, however, can become boring repetitive work. First, the programmer must create a specification document for the proposed file structure. Next, the programmer must implement save and restore functions that convert object data to & from primitive data types, and test it with sample data.

If the application later requires new data to be stored, the file specification must be modified, as well as the save and restore methods. Take it from someone who's been there - creating save & restore functions is not a fun task.

The solution to this is object serialization. Object serialization takes an object's state, and converts it to a stream of data for you. With object serialization, its an easy task to take any object, and make it persistent, without writing custom code to save object member variables. The object can be restored at a later time, and even a later location. With persistence, we can move an object from one computer to another, and have it maintain its state. This very cool feature, in Java, also happens to be very easy to use.

Serializing Objects

Java makes it easy to serialize objects. Any object whose class implements the java.io.Serializable interface can be made persistent with only a few lines of code. No extra methods need to be added to implement the interface, however - the purpose of the interface is to identify at run-time which classes can be safely serialized, and which cannot. You, as a programmer, need only add the implements keyword to your class declaration, to identify your classes as serializable.

public class UserData implements
       java.io.Serializable

Now, once a class is serializable, we can write the object to any OutputStream, such as to disk or a socket connection. To achieve this, we must first create an instance of java.io.ObjectOutputStream, and pass the constructor an existing OutputStream instance.

// Write to disk with FileOutputStream
FileOutputStream f_out = new 
        FileOutputStream("myobject.data");

// Write object with ObjectOutputStream
ObjectOutputStream obj_out = new
        ObjectOutputStream (f_out);

// Write object out to disk
obj_out.writeObject ( myObject );

Note that any Java object that implements the serializable interface can be written to an output stream this way - including those that are part of the Java API. Furthermore, any objects that are referenced by a serialized object will also be stored. This means that arrays, vectors, lists, and collections of objects can be saved in the same fashion - without the need to manually save each one. This can lead to significant time and code savings.

Restoring Objects From a Serialized State

Reading objects back is almost as easy. The one catch is that at runtime, you can never be completely sure what type of data to expect. A data stream containing serialized objects may contain a mixture of different object classes, so you need to explicitly cast an object to a particular class. If you've never cast an object before, the procedure is relatively straightforward. First check the object's class, using the instanceof operator. Then cast to the correct class.

// Read from disk using FileInputStream
FileInputStream f_in = new 
        FileInputStream("myobject.data");

// Read object using ObjectInputStream
ObjectInputStream obj_in = 
        new ObjectInputStream (f_in);

// Read an object
Object obj = obj_in.readObject();

if (obj instanceof Vector)
{
        // Cast object to a Vector
        Vector vec = (Vector) obj;

        // Do something with vector....
}

Further Issues With Serialization

As you can see, its relatively easy to serialize an object. Whenever new fields are added to an object, they will be saved automatically, without requiring modification to your save and restore code. However, there are some cases where this behavior is not desirable. For example, a password member variable might not be safe to transmit to third parties over a network connection, and might need to be left blank. In this case, the transient keyword can be used. The transient field indicates that a particular member variable should not be saved. Though not used often, it's an important keyword to remember.

public class UserSession implements 
         java.io.Serializable
{
        String username;
        transient String password;
}

Summary

Java's support for object serialization makes the implementation of persistent objects extremely easy. In contrast, the amount of code required to save and restore every field of an object is complex and repetitive work. While it is certainly possible to write your own serialization mechanism, the simplicity of that provided by Java would be hard to beat.

Serialization benefits programmers by

  • Reducing time taken to write code for save and restoration of object or application state
  • Eliminating complexity of save and restore operations, and avoiding the need for creating a new file format
  • Making it easier for objects to travel over a network connection.

With relatively little effort, you can apply serialization to a variety of tasks. Not only do applications benefit from serialization, but also applets. Rather than specifying a long list of parameters, or performing time consuming initialization and parsing, an applet can simple reload a configuration object whose member variables contain all the information needed to execute. It's not just useful for Java applications - even applets can benefit, by loading their configuration details or parameters. With a little imagination, serialization may just have a place in your next project.

Back to the Web Developer's Journal
Contact WDJ   •    Suits!   •    Propheads!   •    Ponytails!
Discuss   •    Subscribe   •    Search


internet.com

IT | Developer | Internet News | Small Business | Personal Technology | International | Search internet.com | Advertise | Corporate Info
Newsletters | Tech Jobs | E-mail Offers

internet.commerce
Be a Commerce Partner   Logo Design Custom    Car Donations    GPS    Web Design    Compare Prices    Send Text Messages    GPS Devices            
  

JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
Microsoft Article: 7.0, Microsoft's Lucky Version?
Microsoft Article: Hyper-V--The Killer Feature in Windows Server 2008
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Windows Server 2008
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES