[ Team LiB ] 10.4 Bean Serialization As
[ Team LiB ] 10.4 Bean Serialization As discussed in Chapter 3, one of the remarkable features of beans is their ability to store an instance of a bean, perhaps containing some local configuration data, in a file. As mentioned, this requires no special code in the bean; the class must simply implement the java.io.Serializable interface. Listing 10.4 shows a bean with a main method that allows instances to be created, saved, and loaded. Listing 10.4 A bean that uses serialization package com.awl.jspblog.ch10; import java.io.*; import java.util.*; import java.text.*; public class SaveableBean implements Serializable { private Date createTime; private String message; public SaveableBean() { setDate(new Date()); } public void setDate(Date createTime) { this.createTime = createTime; } public Date getDate() {return createTime;} public void setMessage(String message) { this.message = message; } public String getMessage() {return message;} public static void main(String argv[]) throws Exception { if (argv[0].equals(”-create”)) { SaveableBean sb = new SaveableBean(); sb.setMessage(argv[2]); ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream(argv[1])); out.writeObject(sb); out.close(); System.out.println(”Bean created and saved!”); } else if (argv[0].equals(”-load”)) { ObjectInputStream in = new ObjectInputStream( new FileInputStream(argv[1])); SaveableBean sb = (SaveableBean) in.readObject(); in.close(); SimpleDateFormat sdf = new SimpleDateFormat(”hh:mm:ss dd/MM/yy”); Page 188
Note: If you are looking for inexpensive but high quality provider to host and run your serlvet application check Astra servlet hosting services