Hi all,

Im trying to get my head around object persistance, yet im getting nowhere. All i have found is examples of stuff to do with databases.

Can somebody offer an explination for an idiot please.

Regards

Paul

hi thanks for the information.

So objects dont have to die, they can be flattened and saved to a file instead of having to be re-created??

Im working on a library system, with overdue items etc. What could i use serializable on?

I was thinking maybe active book loans?

could you suggest anything that could also use this?

I'm pretty sure you can Serialize any object that implements the Serializable interface. You can serialize the entire library object if you want, which would of course serialize every other object inside it automatically. Read the link I gave you.

Hi,

Ive read that document through 3 times and the examples are good. But i have a couple of questions.

When would you choose to use it?
Can you give me an example of when you have used it?

i dont want code, i just need to understand how i can use it for something useful...

Hi,

Ive read that document through 3 times and the examples are good. But i have a couple of questions.

When would you choose to use it?
Can you give me an example of when you have used it?

i dont want code, i just need to understand how i can use it for something useful...

I've used it in projects to send "Objects" (as data) across Sockets and reuse the Objects on the other side. You could send the Objects as data and have both client and server know the exact format of the data to recreate it, but serializing it is much easier. You can also use it to store data in text files. The use of storing it in text files would largely be the same: it would be much easier to store and retrieve the data than if you wrote your own format style for the text file then read it in using knowledge of that format style.

commented: Great! +6

Storage of data in variables and arrays is temporary – when a local variable goes out of scope or a program terminates, that data is lost.
Files (and databases) are used for long-term storage of data and data that is maintained in files is called persistent data.
There are two fundamentally different formats for storing data:
text format where the data items are stored in formatted data files as character text – such files are convenient for humans since they can be easily created and then viewed using simple editors such as Notepad and emacs.
binary format where data items are stored as a sequence of bytes – binary storage is more compact and therefore more efficient for the storage of data (used for storing audio-visual/multimedia data and compressed data).
Java views data input and output as a flow of bytes known as a data stream
With input/output, there are two broad categories of data:
1. machine-formatted data – represented as a sequence of 0’s and 1’s
2. human-readable data – represented in the form of characters, so when you read a number such as 3.142, you are reading a sequence of characters and interpreting them as a number
To deal with these two broad categories of data, Java has two main categories of data streams – byte streams for machine-formatted data and character streams for human-readable data

How would you store the state of an object? There are two possible techniques:
- attribute storage – in this approach, all the attributes (properties) of an object are stored individually (usually as formatted text)
- object serialisation – with this technique, objects are stored as an entire instance – not only the object’s data (its state), but also information about the data type of those values
With attribute storage, the value of each instance variable is individually written to file (usually in text format) so the state of the object is stored as a formatted text file
To re-construct an object, an application needs to read the individual values back (as strings) and then use the relevant class's setter methods, (or an appropriate conversion constructor if one is provided by the class) to "re-construct" the object

Serialisation is the process of saving an object onto a storage medium in binary form
In Java, to serialise an object means to convert its state to a byte stream in such a way that the byte stream can be reverted back into a copy of the object
The series of bytes and format of the saved object can then be retrieved and used to re-create an object that is identical in its internal state to the original object
With object serialisation, instances can be written to file in a "single" operation and subsequently retrieved together, so there is no need to "re-create" them

Java supports the serialisation of data, whereas C++ does not

We enable object serialisation by requiring its class to implement the Serializable interface

These ideas will be explored where we use both approaches to store and retrieve a Person object – but first we need to look briefly at input/output in Java
To read and write machine-formatted (binary) data, programs should use the byte stream classes, whose names end with InputStream and OutputStream respectively
In particular for applications that read and write to disk files, use the classes FileInputStream and FileOutputStream
These classes are subclasses of InputStream and OutputStream respectively
To read and write character streams (human-readable data), programs should use classes whose names end with Reader and Writer respectively
In particular for applications that read and write to disk files, use the classes FileReader and FileWriter
All such classes are concrete classes that subclass the abstract classes Reader and Writer
For reading machine-formatted (binary data), use one of the subclasses of InputStream
For writing machine-formatted (binary data), use one of the subclasses of OutputStream
For reading human-readable character data use one of the subclasses of Reader
For writing human-readable character data use one of the subclasses of Writer
Hence, the Reader/Writer class hierarchy is character-oriented, while the InputStream/OutputStream class hierarchy is byte-oriented
However, a feature, common to both byte streams and character streams, is that basic streams, readers and writers can process only individual characters or bytes
and so need to be combined with other classes to process lines of text, numerical values, strings or entire objects. E.g., in.readLine(), Casting
Let’s define a Person class (bean) with properties, name and age and write a corresponding application that:

constructs an object, john
saves john to an external formatted text file 
then reads data from another existing text data file, “who.txt” to create a new Person object and
outputs this “new" person's name and age to the command window

To start, we define the Person bean class

public class Person
{
   private String name = "" ; 
   private int age = 16 ;   

   public Person() { }
   public Person(String str, 
                         int n )    
   { 
      name = str ;
      age = n ;
   }
   public String getName()
   {
      return name ;
   }
===========
   public void setName(String str) 
   {
       name = str  ;
   }

   public int getAge()  
   {
      return age ;
   }

   public void setAge( int n )
   {
       age = n  ;
   }
}

The following code shows how the attributes of the object john can be written to the text file, outperson.txt

   // create a Person object 
   Person john = new Person( "John", 23 ) ; 

   File f = new File( "outperson.txt" ) ;

   PrintWriter out = new PrintWriter( f ) ; 

   out.println( john.getName() ); // output name to file
   out.println( john.getAge() );  // output age to file

   out.close() ;  // close the file

Read in the formatted values from the formatted file inperson.txt and create a new object which is a copy of the original Person object – trim() ( a method from Java’s String class) is needed to remove any leading blank spaces

 FileReader reader = new FileReader( “who.txt" ) ;   
 BufferedReader in = new BufferedReader( reader ) ; 

 String strName = in.readLine() ;   
 String str2 = in.readLine() ;   

 int nAge = Integer.parseInt( str2.trim() ) ; 
 Person whoAmI = new Person( strName, nAge ) ;  

Java 1.5 introduced the Scanner class to make this input process easier!

  Scanner in = new Scanner( new File( "who.txt" ) ) ;

  String strName = in.nextLine() ;  // get hold of the name

  int nAge = in.nextInt() ;   // get hold of the age directly

  Person whoAmI = new Person( strName, nAge ) ;

  System.out.println( "Person from formatted text file:\n" +
        whoAmI.getName() + "  is aged " + whoAmI.getAge() ) ;

  in.close() ;   // close file

Let’s now define a SerialisedPerson bean class with the same properties, name and age and write a corresponding application that:
constructs an object, jane
saves jane to an external serialised file
then reads data from another existing serialised file to create a new SerialisedPerson object and
outputs this "new" person's name and age to the command window
To start, we define the SerialisedPerson bean class

import java.io.* ;
public class Person implements
                           Serializable
{
   private String name = "" ; 
   private int age = 16 ;   

   public Person() { }
   public Person(String str, 
                         int n )    
   { 
      name = str ;
      age = n ;
   }
   public String getName()
   {
      return name ;
   }
================
   public void setName(String str) 
   {
       name = str  ;
   }

   public int getAge()  
   {
      return age ;
   }

   public void setAge( int n )
   {
       age = n  ;
   }
}

The following code shows how the object jane can be written to the serialised file, person.ser (note file extension)

  // create a SerialisedPerson object 
  SerializedPerson jane = 
           new SerializedPerson( "Lady Jane Grey", 15 ) ;

  File f = new File( "person.ser" ) ;  

  ObjectOutputStream out = 
     new ObjectOutputStream( new FileOutputStream( f ) ) ;         

  out.writeObject( jane ) ;  // ‘jane’ is written in one go!        
  out.close() ;

Let’s now read in the serialized values from the serialized file person.ser and create a new object which is a clone (copy) of the original SerializedPerson object

  ObjectInputStream in = 
      new ObjectInputStream( new FileInputStream( f ) ) ;

  SerializedPerson person = new SerializedPerson() ; 

  person = (SerializedPerson) in.readObject() ;  // all done in one statement

Variables of the primitive types are serialisable

Subclasses of a class implementing the Serializable interface are themselves serializable and do not need to explicitly include this in their header

In a class that implements Serializable, the programmer must ensure that every instance variable of the class is a serializable type – or must declare particular instance variables as transient to indicate that those variables are not serialisable and should be ignored during the serialisable process
(transient variable is a variable that may not be serialized. The transient variable is not persist when an object is stored )

An ObjectOutputStream will not output an object unless it is a serialisable object

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.