The object to be serialised must implement the Serializable
interface or inherit it. If you don't want fields in the object serialised mark them as transient
.
Serializing an Object
//the object to serialize Date date=new Date() ; //the file to serialize to String filename="date.ser"; //write the object to file FileOutputStream fos=new FileOutputStream(filename); BufferedOutputStream bos=new BufferedOutputStream(fos); ObjectOutputStream outputStream=new ObjectOutputStream(bos); outputStream.writeObject(date); outputStream.flush(); outputStream.close();De-Serializing an Object
//the file containing the serialized object String filename="date.ser"; //read the object from the file FileInputStream fis=new FileInputStream(filename); BufferedInputStream bis=new BufferedInputStream(fis); ObjectInputStream inputStream=new ObjectInputStream(bis); Date date=(Date)inputStream.readObject(); inputStream.close(); //print the object System.out.println(date);Determining the Size of an Object
//the object to measure Date date=new Date() ; //write it out to a byte array ByteArrayOutputStream baos=new ByteArrayOutputStream(); ObjectOutputStream oos=new ObjectOutputStream(baos); oos.writeObject(date); oos.close(); byte[] ba=baos.toByteArray(); baos.close(); //print size System.out.println(ba.length);or you can serialize the object to a file and measure the size of the file.
you have a nice site. thanks for sharing this site. there are various kinds of ebooks are available here
ReplyDeletehttp://feboook.blogspot.com
Hello this is a nice site.Do you also do C programming?
ReplyDeletehttp://www.mycsnippets.blogspot.com/