| Real'sHowTo |
|
|
Custom Search
|
| Real'sHowTo |
|
|
Custom Search
|
private void writeObject(java.io.ObjectOutputStream out)
throws IOException
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException;
In the following snippet, we use a Vector to simulate a Queue.
First the Queue state is saved to a file.
Then rename main to main_serialize and main_reload to main and compile. Now the snippet read the file to reload the Queue from the data previously saved.
import java.util.Vector;
import java.io.*;
public class Queue extends Vector {
/*
** FIFO
*/
Queue() {
super();
}
void put(Object o) {
addElement(o);
}
Object get() {
if (isEmpty()) return null;
Object o = firstElement();
removeElement(o);
return o;
}
Object peek() {
if (isEmpty()) return null;
return firstElement();
}
public static void main(String args[]) {
Queue theQueue;
theQueue = new Queue();
theQueue.put("element 1");
theQueue.put("element 2");
theQueue.put("element 3");
theQueue.put("element 4");
System.out.println(theQueue.toString());
// serialize the Queue
System.out.println("serializing theQueue");
try {
FileOutputStream fout = new FileOutputStream("thequeue.dat");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(theQueue);
oos.close();
}
catch (Exception e) { e.printStackTrace(); }
}
public static void main_load(String args[]) {
Queue theQueue;
theQueue = new Queue();
// unserialize the Queue
System.out.println("unserializing theQueue");
try {
FileInputStream fin = new FileInputStream("thequeue.dat");
ObjectInputStream ois = new ObjectInputStream(fin);
theQueue = (Queue) ois.readObject();
ois.close();
}
catch (Exception e) { e.printStackTrace(); }
System.out.println(theQueue.toString());
}
}
Note : See this How-to to serialize using XML format.
joafip( java data object persistence in file ) at http://joafip.sourceforge.net.
Written and compiled by Réal Gagnon ©1998-2013
[ home ]