Java is a fully object-oriented high-level language, so data is mostly stored in objects during programming. Sometimes we need to write the entire object in the memory to the file, and then restore the object from the file to the memory at the appropriate time. We can use the java. io. ObjectInputStream and java. io. ObjectOutputStream classes to complete this task.
1. Serialize)
Serialization refers to the process of converting the object state information into a form that can be stored or transmitted. During serialization, the object writes its current state to the temporary or persistent storage area. Later, you can re-create the object by reading or deserializing the object status from the bucket.
2. ObjectInputStream and ObjectOutputStream
If we want to serialize an object, such as a Custom User class object, this object must implement the Serializable interface. The Serializable interface does not have any abstract method. It is implemented only to notify the compiler that the object will be serialized. Similar uses include the Cloneable interface, which only serves to notify the compiler.
To demonstrate how to serialize objects, we first design a User class:
[Java]
Package cls;
Import java. io .*;
Public class User implements Serializable // implement the Serializable interface, only to identify the Serializable effect of this class
{
// Version of the serializable object
Private static final long serialVersionUID = 1L;
Private String name;
Private int num;
Public User (String name, int num)
{
This. name = name;
This. num = num;
}
Public String getName ()
{
Return name;
}
Public int getNum ()
{
Return num;
}
}
Package cls;
Import java. io .*;
Public class User implements Serializable // implement the Serializable interface, only to identify the Serializable effect of this class
{
// Version of the serializable object
Private static final long serialVersionUID = 1L;
Private String name;
Private int num;
Public User (String name, int num)
{
This. name = name;
This. num = num;
}
Public String getName ()
{
Return name;
}
Public int getNum ()
{
Return num;
}
}
Note that seriaVersionUID is the version of the serializable object. If this version is not specified, the compiler automatically generates a seriaVersionUID for the class that implements the Serializable interface. If it is automatically generated, if the User class is changed once, the automatically generated seriaVersionUID will be different. When reading back objects from a file, if the seriaVersionUID of the two objects is different, java. io. InvalidClassException will be thrown. Therefore, if we do not need to change the User class in the future, we 'd better specify the seriaVersionUID to avoid this exception.
Next we use the ObjectInputStream class and ObjectOutputStream class to write three User objects to the file, append one User object, and finally read the objects back from the file.
[Java]
Package cls;
Import java. io .*;
Import java. util .*;
Import cls. User;
Public class ObjectStreamDemo
{
Public static void main (String [] args)
{
User [] user = new User [] {new User ("dogg", 1), new User ("catt", 2), new User ("pigg ", 3 )};
// Write the object to the file
Try
{
ObjectStreamDemo. writeObj (user, args [0]);
}
Catch (Exception e)
{
System. out. println (e. toString ());
}
// Append an object to the object
Try
{
// Object to be appended
User [] u = new User [] {new User ("append1", 4), new User ("append2", 5 )};
ObjectStreamDemo. appendObj (u, args [0]);
}
Catch (Exception e)
{
System. out. println (e. toString ());
}
// Read the object
Try
{
List <User> list = ObjectStreamDemo. readObj (args [0]);
// Output Object Information
Iterator <User> it = list. iterator ();
While (it. hasNext ())
{
User temp = it. next ();
System. out. println (temp. getName () + "," + temp. getNum ());
}
}
Catch (Exception e)
{
System. out. println (e. toString ());
}
}
Static private void appendObj (Object [] objs, String fileName) throws Exception
{
File file = new File (fileName );
// Create a file stream object in append Mode
FileOutputStream FCM = new FileOutputStream (file, true );
ObjectOutputStream oos = new ObjectOutputStream (FCM)
{
// Rewrite the writeStreamHeader () method, empty implement
Protected void writeStreamHeader (){};
};
// Write data
For (Object o: objs)
{
Oos. writeObject (o );
}
// Close the stream
Oos. close ();
}
Static private List <User> readObj (String fileName) throws Exception
{
File file = new File (fileName );
// Use List to save the read object
ArrayList <User> list = new ArrayList <User> ();
// Create a stream object
FileInputStream FCM = new FileInputStream (file );
ObjectInputStream ois = new ObjectInputStream (FCM );
// Read the object and put it in the List container
While (FCM. available ()> 0)
{
List. add (User) ois. readObject ());
}
Ois. close ();
Return list; // return List
}
Static private void writeObj (Object [] objs, String fileName) throws Exception
{
// Use the file name specified in the command line parameters
File file = new File (fileName );
// Create a stream object
ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream (file ));
// Write object
For (Object o: objs)
{
Oos. writeObject (o );
}
// Close the stream
Oos. close ();
}
}
Package cls;
Import java. io .*;
Import java. util .*;
Import cls. User;
Public class ObjectStreamDemo
{
Public static void main (String [] args)
{
User [] user = new User [] {new User ("dogg", 1), new User ("catt", 2), new User ("pigg ", 3 )};
// Write the object to the file
Try
{
ObjectStreamDemo. writeObj (user, args [0]);
}
Catch (Exception e)
{
System. out. println (e. toString ());
}
// Append an object to the object
Try
{
// Object to be appended
User [] u = new User [] {new User ("append1", 4), new User ("append2", 5 )};
ObjectStreamDemo. appendObj (u, args [0]);
}
Catch (Exception e)
{
System. out. println (e. toString ());
}
// Read the object
Try
{
List <User> list = ObjectStreamDemo. readObj (args [0]);
// Output Object Information
Iterator <User> it = list. iterator ();
While (it. hasNext ())
{
User temp = it. next ();
System. out. println (temp. getName () + "," + temp. getNum ());
}
}
Catch (Exception e)
{
System. out. println (e. toString ());
}
}
Static private void appendObj (Object [] objs, String fileName) throws Exception
{
File file = new File (fileName );
// Create a file stream object in append Mode
FileOutputStream FCM = new FileOutputStream (file, true );
ObjectOutputStream oos = new ObjectOutputStream (FCM)
{
// Rewrite the writeStreamHeader () method, empty implement
Protected void writeStreamHeader (){};
};
// Write data
For (Object o: objs)
{
Oos. writeObject (o );
}
// Close the stream
Oos. close ();
}
Static private List <User> readObj (String fileName) throws Exception
{
File file = new File (fileName );
// Use List to save the read object
ArrayList <User> list = new ArrayList <User> ();
// Create a stream object
FileInputStream FCM = new FileInputStream (file );
ObjectInputStream ois = new ObjectInputStream (FCM );
// Read the object and put it in the List container
While (FCM. available ()> 0)
{
List. add (User) ois. readObject ());
}
Ois. close ();
Return list; // return List
}
Static private void writeObj (Object [] objs, String fileName) throws Exception
{
// Use the file name specified in the command line parameters
File file = new File (fileName );
// Create a stream object
ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream (file ));
// Write object
For (Object o: objs)
{
Oos. writeObject (o );
}
// Close the stream
Oos. close ();
}
}
Note: When we want to append an object to an existing file, we should rewrite the writeStreamHeader () method of ObjectOutputStream and implement it empty. Because ObjectOutputStream adds a special Stream Header when writing data. It checks the Stream Header before reading data. So when we append an object to the object, ObjectOutputStream will write the stream header to the object again, so that the StreamCorrupedException exception will occur when the object is read.