110 likes | 234 Views
This document provides an in-depth overview of how to implement serializable objects in Java to facilitate data streaming. It explains the concept of serialization, the Serializable interface, and how to convert objects into a reliable data stream. By utilizing classes like `ObjectInputStream` and `ObjectOutputStream`, you will learn how to read from and write to files using serialized data. The content targets developers looking to improve their data handling practices in Java, providing examples such as an `infoClass` that contains attributes like name and age.
E N D
A Document Dear John, I think we should just be friends… 68 101 97 114 20 74 111 104 110 44 D e a r J o h n ,
A serial data “STREAM” 68 101 97 114 20 74 111 104 110 44 68 101 97 114 20 74 111 104 110 44
Storage on disk SOF 68 101 97 114 74 111 104 110 44 EOF “streamed” to disk (an output) SOF 68 101 97 114 20 74 111 104 110 44 EOF Dear John, streamed from disk (an input)
class infoClass { public String Name; public int Age; public infoClass( String n, int a ) { Name = n; Age = a; } } infoClass infoObject = new infoClass ( “Sherlock Holmes”, 39 ); Objects contain methods and info Contains info, so size is known and finite Contains no info, just placeholders
Serializable - means “in a row” Sherlock Holmes 39 OBJECT turn into a data stream 83 104 101 114108 111 99 107…
Serializable interface class infoClass implements Serializable { String Name; int Age; } • means that objects of this class can be turned into an orderly dependable data stream
the Serializable Interface • no methods are involved, so you don’t have to write anything • called a “tagging” interface, because Java just adds variables to your object, to keep the place of your variables in a data stream • Objects that are serializable can be used by “streaming classes”: file I/O, network I/O
what the computer does… class infoClass implements Serializable { String Name; int placeOfName = 1; int sizeOfName = 10; // bytes int Age; int placeofAge = 11; int sizeOfAge = 4; // bytes }
from the byte array ByteArrayInputStream bais = new ByteArrayInputStream( byteArray ) ObjectInputStream ois = new ObjectInputStream( bais ); AnyClass newObject = (AnyClass)ois.readObject(); ois.close();
to and from streams • to a file: FileOutputStream target = new FileOutputStream("filename.ser"); ObjectOutputStream out = new ObjectOutputStream( target ); out.writeObject( anyObject ); out.close(); • from a file: FileInputStream source = new FileInputStream( "filename.ser" ); ObjectInputStream in = new ObjectInputStream( source ); AnyClass newObject = (AnyClass) in.readObject(); in.close();